VCAI.cpp 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868
  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. const CBuilding * buildPtr = t->town->buildings.at(building);
  795. auto toBuild = buildPtr->requirements.getFulfillmentCandidates([&](const BuildingID & buildID)
  796. {
  797. return t->hasBuilt(buildID);
  798. });
  799. toBuild.push_back(building);
  800. for(BuildingID buildID : toBuild)
  801. {
  802. EBuildingState::EBuildingState canBuild = cb->canBuildStructure(t, buildID);
  803. if (canBuild == EBuildingState::HAVE_CAPITAL
  804. || canBuild == EBuildingState::FORBIDDEN
  805. || canBuild == EBuildingState::NO_WATER)
  806. return false; //we won't be able to build this
  807. }
  808. if (maxDays && toBuild.size() > maxDays)
  809. return false;
  810. TResources currentRes = cb->getResourceAmount();
  811. TResources income = estimateIncome();
  812. //TODO: calculate if we have enough resources to build it in maxDays
  813. for(const auto & buildID : toBuild)
  814. {
  815. const CBuilding *b = t->town->buildings.at(buildID);
  816. EBuildingState::EBuildingState canBuild = cb->canBuildStructure(t, buildID);
  817. if(canBuild == EBuildingState::ALLOWED)
  818. {
  819. if(!containsSavedRes(b->resources))
  820. {
  821. logAi->debugStream() << boost::format("Player %d will build %s in town of %s at %s") % playerID % b->Name() % t->name % t->pos;
  822. cb->buildBuilding(t, buildID);
  823. return true;
  824. }
  825. continue;
  826. }
  827. else if(canBuild == EBuildingState::NO_RESOURCES)
  828. {
  829. TResources cost = t->town->buildings.at(buildID)->resources;
  830. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  831. {
  832. int diff = currentRes[i] - cost[i] + income[i];
  833. if(diff < 0)
  834. saving[i] = 1;
  835. }
  836. continue;
  837. }
  838. else if (canBuild == EBuildingState::PREREQUIRES)
  839. {
  840. // can happen when dependencies have their own missing dependencies
  841. if (tryBuildStructure(t, buildID, maxDays - 1))
  842. return true;
  843. }
  844. else if (canBuild == EBuildingState::MISSING_BASE)
  845. {
  846. if (tryBuildStructure(t, b->upgrade, maxDays - 1))
  847. return true;
  848. }
  849. }
  850. return false;
  851. }
  852. bool VCAI::tryBuildAnyStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays)
  853. {
  854. for(const auto & building : buildList)
  855. {
  856. if(t->hasBuilt(building))
  857. continue;
  858. if (tryBuildStructure(t, building, maxDays))
  859. return true;
  860. }
  861. return false; //Can't build anything
  862. }
  863. bool VCAI::tryBuildNextStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays)
  864. {
  865. for(const auto & building : buildList)
  866. {
  867. if(t->hasBuilt(building))
  868. continue;
  869. return tryBuildStructure(t, building, maxDays);
  870. }
  871. return false;//Nothing to build
  872. }
  873. void VCAI::buildStructure(const CGTownInstance * t)
  874. {
  875. //TODO make *real* town development system
  876. //TODO: faction-specific development: use special buildings, build dwellings in better order, etc
  877. //TODO: build resource silo, defences when needed
  878. //Possible - allow "locking" on specific building (build prerequisites and then building itself)
  879. //Set of buildings for different goals. Does not include any prerequisites.
  880. const BuildingID essential[] = {BuildingID::TAVERN, BuildingID::TOWN_HALL};
  881. const BuildingID goldSource[] = {BuildingID::TOWN_HALL, BuildingID::CITY_HALL, BuildingID::CAPITOL};
  882. const BuildingID unitsSource[] = { BuildingID::DWELL_LVL_1, BuildingID::DWELL_LVL_2, BuildingID::DWELL_LVL_3,
  883. BuildingID::DWELL_LVL_4, BuildingID::DWELL_LVL_5, BuildingID::DWELL_LVL_6, BuildingID::DWELL_LVL_7};
  884. const BuildingID unitsUpgrade[] = { BuildingID::DWELL_LVL_1_UP, BuildingID::DWELL_LVL_2_UP, BuildingID::DWELL_LVL_3_UP,
  885. BuildingID::DWELL_LVL_4_UP, BuildingID::DWELL_LVL_5_UP, BuildingID::DWELL_LVL_6_UP, BuildingID::DWELL_LVL_7_UP};
  886. const BuildingID unitGrowth[] = { BuildingID::FORT, BuildingID::CITADEL, BuildingID::CASTLE, BuildingID::HORDE_1,
  887. BuildingID::HORDE_1_UPGR, BuildingID::HORDE_2, BuildingID::HORDE_2_UPGR};
  888. const BuildingID spells[] = {BuildingID::MAGES_GUILD_1, BuildingID::MAGES_GUILD_2, BuildingID::MAGES_GUILD_3,
  889. BuildingID::MAGES_GUILD_4, BuildingID::MAGES_GUILD_5};
  890. const BuildingID extra[] = {BuildingID::RESOURCE_SILO, BuildingID::SPECIAL_1, BuildingID::SPECIAL_2, BuildingID::SPECIAL_3,
  891. BuildingID::SPECIAL_4, BuildingID::SHIPYARD}; // all remaining buildings
  892. TResources currentRes = cb->getResourceAmount();
  893. TResources income = estimateIncome();
  894. if (tryBuildAnyStructure(t, std::vector<BuildingID>(essential, essential + ARRAY_COUNT(essential))))
  895. return;
  896. //we're running out of gold - try to build something gold-producing. Multiplier can be tweaked, 6 is minimum due to buildings costs
  897. if (currentRes[Res::GOLD] < income[Res::GOLD] * 6)
  898. if (tryBuildNextStructure(t, std::vector<BuildingID>(goldSource, goldSource + ARRAY_COUNT(goldSource))))
  899. return;
  900. if (cb->getDate(Date::DAY_OF_WEEK) > 6)// last 2 days of week - try to focus on growth
  901. {
  902. if (tryBuildNextStructure(t, std::vector<BuildingID>(unitGrowth, unitGrowth + ARRAY_COUNT(unitGrowth)), 2))
  903. return;
  904. }
  905. // first in-game week or second half of any week: try build dwellings
  906. if (cb->getDate(Date::DAY) < 7 || cb->getDate(Date::DAY_OF_WEEK) > 3)
  907. if (tryBuildAnyStructure(t, std::vector<BuildingID>(unitsSource, unitsSource + ARRAY_COUNT(unitsSource)), 8 - cb->getDate(Date::DAY_OF_WEEK)))
  908. return;
  909. //try to upgrade dwelling
  910. for(int i = 0; i < ARRAY_COUNT(unitsUpgrade); i++)
  911. {
  912. if (t->hasBuilt(unitsSource[i]) && !t->hasBuilt(unitsUpgrade[i]))
  913. {
  914. if (tryBuildStructure(t, unitsUpgrade[i]))
  915. return;
  916. }
  917. }
  918. //remaining tasks
  919. if (tryBuildNextStructure(t, std::vector<BuildingID>(goldSource, goldSource + ARRAY_COUNT(goldSource))))
  920. return;
  921. if (tryBuildNextStructure(t, std::vector<BuildingID>(spells, spells + ARRAY_COUNT(spells))))
  922. return;
  923. if (tryBuildAnyStructure(t, std::vector<BuildingID>(extra, extra + ARRAY_COUNT(extra))))
  924. return;
  925. }
  926. std::vector<const CGObjectInstance *> VCAI::getPossibleDestinations(HeroPtr h)
  927. {
  928. validateVisitableObjs();
  929. std::vector<const CGObjectInstance *> possibleDestinations;
  930. for(const CGObjectInstance *obj : visitableObjs)
  931. {
  932. if(isAccessibleForHero(obj->visitablePos(), h) && !obj->wasVisited(playerID) &&
  933. (obj->tempOwner != playerID || isWeeklyRevisitable(obj))) //flag or get weekly resources / creatures
  934. possibleDestinations.push_back(obj);
  935. }
  936. boost::sort(possibleDestinations, isCloser);
  937. possibleDestinations.erase(boost::remove_if(possibleDestinations, [&](const CGObjectInstance *obj) -> bool
  938. {
  939. const int3 pos = obj->visitablePos();
  940. if(vstd::contains(alreadyVisited, obj))
  941. return true;
  942. if(!isSafeToVisit(h, pos))
  943. return true;
  944. if (!shouldVisit(h, obj))
  945. return true;
  946. if (vstd::contains(reservedObjs, obj)) //does checking for our own reserved objects make sense? here?
  947. return true;
  948. const CGObjectInstance *topObj = cb->getVisitableObjs(pos).back(); //it may be hero visiting this obj
  949. //we don't try visiting object on which allied or owned hero stands
  950. // -> it will just trigger exchange windows and AI will be confused that obj behind doesn't get visited
  951. if(topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES)
  952. return true;
  953. return false;
  954. }),possibleDestinations.end());
  955. return possibleDestinations;
  956. }
  957. void VCAI::wander(HeroPtr h)
  958. {
  959. while(1)
  960. {
  961. validateVisitableObjs();
  962. std::vector <ObjectIdRef> dests, tmp;
  963. range::copy(reservedHeroesMap[h], std::back_inserter(tmp)); //visit our reserved objects first
  964. for (auto obj : tmp)
  965. {
  966. if (isAccessibleForHero (obj->visitablePos(), h)) //even nearby objects could be blocked by other heroes :(
  967. dests.push_back(obj); //can't use lambda for member function :(
  968. }
  969. if (!dests.size())
  970. range::copy(getPossibleDestinations(h), std::back_inserter(dests));
  971. if(!dests.size())
  972. {
  973. auto compareReinforcements = [h](const CGTownInstance *lhs, const CGTownInstance *rhs) -> bool
  974. {
  975. return howManyReinforcementsCanGet(h, lhs) < howManyReinforcementsCanGet(h, rhs);
  976. };
  977. std::vector<const CGTownInstance *> townsReachable;
  978. std::vector<const CGTownInstance *> townsNotReachable;
  979. for(const CGTownInstance *t : cb->getTownsInfo())
  980. {
  981. if(!t->visitingHero && howManyReinforcementsCanGet(h,t) && !vstd::contains(townVisitsThisWeek[h], t))
  982. {
  983. if (isAccessibleForHero (t->visitablePos(), h))
  984. townsReachable.push_back(t);
  985. else
  986. townsNotReachable.push_back(t);
  987. }
  988. }
  989. if(townsReachable.size())
  990. {
  991. boost::sort(townsReachable, compareReinforcements);
  992. dests.emplace_back(townsReachable.back());
  993. }
  994. else if(townsNotReachable.size())
  995. {
  996. boost::sort(townsNotReachable, compareReinforcements);
  997. //TODO pick the truly best
  998. const CGTownInstance *t = townsNotReachable.back();
  999. 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();
  1000. int3 pos1 = h->pos;
  1001. striveToGoal(sptr(Goals::VisitTile(t->visitablePos()).sethero(h)));
  1002. if (pos1 == h->pos && h == primaryHero()) //hero can't move
  1003. {
  1004. if(cb->getResourceAmount(Res::GOLD) >= HERO_GOLD_COST && cb->getHeroesInfo().size() < ALLOWED_ROAMING_HEROES && cb->getAvailableHeroes(t).size())
  1005. recruitHero(t);
  1006. }
  1007. break;
  1008. }
  1009. else if(cb->getResourceAmount(Res::GOLD) >= HERO_GOLD_COST)
  1010. {
  1011. std::vector<const CGTownInstance *> towns = cb->getTownsInfo();
  1012. erase_if(towns, [](const CGTownInstance *t) -> bool
  1013. {
  1014. for(const CGHeroInstance *h : cb->getHeroesInfo())
  1015. if(!t->getArmyStrength() || howManyReinforcementsCanGet(h, t))
  1016. return true;
  1017. return false;
  1018. });
  1019. boost::sort(towns, compareArmyStrength);
  1020. if(towns.size())
  1021. recruitHero(towns.back());
  1022. break;
  1023. }
  1024. else
  1025. {
  1026. logAi->debugStream() << "Nowhere more to go...";
  1027. break;
  1028. }
  1029. }
  1030. const ObjectIdRef&dest = dests.front();
  1031. logAi->debugStream() << boost::format("Of all %d destinations, object oid=%d seems nice") % dests.size() % dest.id.getNum();
  1032. if(!goVisitObj(dest, h))
  1033. {
  1034. if(!dest)
  1035. {
  1036. logAi->debugStream() << boost::format("Visit attempt made the object (id=%d) gone...") % dest.id.getNum();
  1037. }
  1038. else
  1039. {
  1040. logAi->debugStream() << boost::format("Hero %s apparently used all MPs (%d left)") % h->name % h->movement;
  1041. reserveObject(h, dest); //reserve that object - we predict it will be reached soon
  1042. //removed - do not forget abstract goal so easily
  1043. //setGoal(h, CGoal(VISIT_TILE).sethero(h).settile(dest->visitablePos()));
  1044. }
  1045. break;
  1046. }
  1047. if(h->visitedTown)
  1048. {
  1049. townVisitsThisWeek[h].push_back(h->visitedTown);
  1050. buildArmyIn(h->visitedTown);
  1051. break;
  1052. }
  1053. }
  1054. }
  1055. void VCAI::setGoal(HeroPtr h, Goals::TSubgoal goal)
  1056. { //TODO: check for presence?
  1057. if (goal->invalid())
  1058. erase_if_present(lockedHeroes, h);
  1059. else
  1060. {
  1061. lockedHeroes[h] = goal;
  1062. goal->setisElementar(false); //always evaluate goals before realizing
  1063. }
  1064. }
  1065. void VCAI::completeGoal (Goals::TSubgoal goal)
  1066. {
  1067. logAi->debugStream() << boost::format("Completing goal: %s") % goal->name();
  1068. if (const CGHeroInstance * h = goal->hero.get(true))
  1069. {
  1070. auto it = lockedHeroes.find(h);
  1071. if (it != lockedHeroes.end())
  1072. if (it->second == goal)
  1073. {
  1074. logAi->debugStream() << boost::format("%s") % goal->completeMessage();
  1075. lockedHeroes.erase(it); //goal fulfilled, free hero
  1076. }
  1077. }
  1078. else //complete goal for all heroes maybe?
  1079. {
  1080. for (auto p : lockedHeroes)
  1081. {
  1082. if (p.second == goal || p.second->fulfillsMe(goal)) //we could have fulfilled goals of other heroes by chance
  1083. {
  1084. logAi->debugStream() << boost::format("%s") % p.second->completeMessage();
  1085. lockedHeroes.erase (lockedHeroes.find(p.first)); //is it safe?
  1086. }
  1087. }
  1088. }
  1089. }
  1090. void VCAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side)
  1091. {
  1092. NET_EVENT_HANDLER;
  1093. assert(playerID > PlayerColor::PLAYER_LIMIT || status.getBattle() == UPCOMING_BATTLE);
  1094. status.setBattle(ONGOING_BATTLE);
  1095. 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
  1096. battlename = boost::str(boost::format("Starting battle of %s attacking %s at %s") % (hero1 ? hero1->name : "a army") % (presumedEnemy ? presumedEnemy->hoverName : "unknown enemy") % tile);
  1097. CAdventureAI::battleStart(army1, army2, tile, hero1, hero2, side);
  1098. }
  1099. void VCAI::battleEnd(const BattleResult *br)
  1100. {
  1101. NET_EVENT_HANDLER;
  1102. assert(status.getBattle() == ONGOING_BATTLE);
  1103. status.setBattle(ENDING_BATTLE);
  1104. bool won = br->winner == myCb->battleGetMySide();
  1105. logAi->debugStream() << boost::format("Player %d: I %s the %s!") % playerID % (won ? "won" : "lost") % battlename;
  1106. battlename.clear();
  1107. CAdventureAI::battleEnd(br);
  1108. }
  1109. void VCAI::waitTillFree()
  1110. {
  1111. auto unlock = vstd::makeUnlockSharedGuard(cb->getGsMutex());
  1112. status.waitTillFree();
  1113. }
  1114. void VCAI::markObjectVisited (const CGObjectInstance *obj)
  1115. {
  1116. if(dynamic_cast<const CGVisitableOPH *>(obj) || //we may want to wisit it with another hero
  1117. dynamic_cast<const CGBonusingObject *>(obj) || //or another time
  1118. (obj->ID == Obj::MONSTER))
  1119. return;
  1120. alreadyVisited.push_back(obj);
  1121. }
  1122. void VCAI::reserveObject(HeroPtr h, const CGObjectInstance *obj)
  1123. {
  1124. reservedObjs.push_back(obj);
  1125. reservedHeroesMap[h].push_back(obj);
  1126. logAi->debugStream() << "reserved object id=" << obj->id << "; address=" << (intptr_t)obj << "; name=" << obj->getHoverText();
  1127. }
  1128. void VCAI::validateVisitableObjs()
  1129. {
  1130. std::vector<const CGObjectInstance *> hlp;
  1131. retreiveVisitableObjs(hlp, true);
  1132. std::string errorMsg;
  1133. auto shouldBeErased = [&](const CGObjectInstance *obj) -> bool
  1134. {
  1135. if(!vstd::contains(hlp, obj))
  1136. {
  1137. logAi->errorStream() << helperObjInfo[obj].name << " at " << helperObjInfo[obj].pos << errorMsg;
  1138. return true;
  1139. }
  1140. return false;
  1141. };
  1142. //errorMsg is captured by ref so lambda will take the new text
  1143. errorMsg = " shouldn't be on the visitable objects list!";
  1144. erase_if(visitableObjs, shouldBeErased);
  1145. for(auto &p : reservedHeroesMap)
  1146. {
  1147. errorMsg = " shouldn't be on list for hero " + p.first->name + "!";
  1148. erase_if(p.second, shouldBeErased);
  1149. }
  1150. errorMsg = " shouldn't be on the reserved objs list!";
  1151. erase_if(reservedObjs, shouldBeErased);
  1152. //TODO overkill, hidden object should not be removed. However, we can't know if hidden object is erased from game.
  1153. errorMsg = " shouldn't be on the already visited objs list!";
  1154. erase_if(alreadyVisited, shouldBeErased);
  1155. }
  1156. void VCAI::retreiveVisitableObjs(std::vector<const CGObjectInstance *> &out, bool includeOwned /*= false*/) const
  1157. {
  1158. foreach_tile_pos([&](const int3 &pos)
  1159. {
  1160. for(const CGObjectInstance *obj : myCb->getVisitableObjs(pos, false))
  1161. {
  1162. if(includeOwned || obj->tempOwner != playerID)
  1163. out.push_back(obj);
  1164. }
  1165. });
  1166. }
  1167. std::vector<const CGObjectInstance *> VCAI::getFlaggedObjects() const
  1168. {
  1169. std::vector<const CGObjectInstance *> ret;
  1170. retreiveVisitableObjs(ret, true);
  1171. erase_if(ret, [](const CGObjectInstance *obj)
  1172. {
  1173. return obj->tempOwner != ai->playerID;
  1174. });
  1175. return ret;
  1176. }
  1177. void VCAI::addVisitableObj(const CGObjectInstance *obj)
  1178. {
  1179. visitableObjs.push_back(obj);
  1180. helperObjInfo[obj] = ObjInfo(obj);
  1181. }
  1182. const CGObjectInstance * VCAI::lookForArt(int aid) const
  1183. {
  1184. for(const CGObjectInstance *obj : ai->visitableObjs)
  1185. {
  1186. if(obj->ID == 5 && obj->subID == aid)
  1187. return obj;
  1188. }
  1189. return nullptr;
  1190. //TODO what if more than one artifact is available? return them all or some slection criteria
  1191. }
  1192. bool VCAI::isAccessible(const int3 &pos)
  1193. {
  1194. //TODO precalculate for speed
  1195. for(const CGHeroInstance *h : cb->getHeroesInfo())
  1196. {
  1197. if(isAccessibleForHero(pos, h))
  1198. return true;
  1199. }
  1200. return false;
  1201. }
  1202. HeroPtr VCAI::getHeroWithGrail() const
  1203. {
  1204. for(const CGHeroInstance *h : cb->getHeroesInfo())
  1205. if(h->hasArt(2)) //grail
  1206. return h;
  1207. return nullptr;
  1208. }
  1209. const CGObjectInstance * VCAI::getUnvisitedObj(const std::function<bool(const CGObjectInstance *)> &predicate)
  1210. {
  1211. //TODO smarter definition of unvisited
  1212. for(const CGObjectInstance *obj : visitableObjs)
  1213. if(predicate(obj) && !vstd::contains(alreadyVisited, obj))
  1214. return obj;
  1215. return nullptr;
  1216. }
  1217. bool VCAI::isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies /*= false*/) const
  1218. {
  1219. cb->setSelection(*h);
  1220. if (!includeAllies)
  1221. { //don't visit tile occupied by allied hero
  1222. for (auto obj : cb->getVisitableObjs(pos))
  1223. {
  1224. if (obj->ID == Obj::HERO && obj->tempOwner == h->tempOwner && obj != h.get())
  1225. return false;
  1226. }
  1227. }
  1228. return cb->getPathInfo(pos)->reachable();
  1229. }
  1230. bool VCAI::moveHeroToTile(int3 dst, HeroPtr h)
  1231. {
  1232. logAi->debugStream() << boost::format("Moving hero %s to tile %s") % h->name % dst;
  1233. int3 startHpos = h->visitablePos();
  1234. bool ret = false;
  1235. if(startHpos == dst)
  1236. {
  1237. //FIXME: this assertion fails also if AI moves onto defeated guarded object
  1238. assert(cb->getVisitableObjs(dst).size() > 1); //there's no point in revisiting tile where there is no visitable object
  1239. cb->moveHero(*h, CGHeroInstance::convertPosition(dst, true));
  1240. waitTillFree(); //movement may cause battle or blocking dialog
  1241. ret = true;
  1242. }
  1243. else
  1244. {
  1245. CGPath path;
  1246. cb->getPath2(dst, path);
  1247. if(path.nodes.empty())
  1248. {
  1249. logAi->errorStream() << "Hero " << h->name << " cannot reach " << dst;
  1250. //setGoal(h, INVALID);
  1251. completeGoal (sptr(Goals::VisitTile(dst).sethero(h))); //TODO: better mechanism to determine goal
  1252. cb->recalculatePaths();
  1253. throw std::runtime_error("Wrong move order!");
  1254. }
  1255. int i=path.nodes.size()-1;
  1256. for(; i>0; i--)
  1257. {
  1258. //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  1259. if(path.nodes[i-1].turns)
  1260. {
  1261. //blockedHeroes.insert(h); //to avoid attempts of moving heroes with very little MPs
  1262. break;
  1263. }
  1264. int3 endpos = path.nodes[i-1].coord;
  1265. if(endpos == h->visitablePos())
  1266. //if (endpos == h->pos)
  1267. continue;
  1268. // if(i > 1)
  1269. // {
  1270. // int3 afterEndPos = path.nodes[i-2].coord;
  1271. // if(afterEndPos.z != endpos.z)
  1272. //
  1273. // }
  1274. //logAi->debugStream() << "Moving " << h->name << " from " << h->getPosition() << " to " << endpos;
  1275. cb->moveHero(*h, CGHeroInstance::convertPosition(endpos, true));
  1276. waitTillFree(); //movement may cause battle or blocking dialog
  1277. boost::this_thread::interruption_point();
  1278. if(!h) //we lost hero - remove all tasks assigned to him/her
  1279. {
  1280. lostHero(h);
  1281. //we need to throw, otherwise hero will be assigned to sth again
  1282. throw std::runtime_error("Hero was lost!");
  1283. }
  1284. }
  1285. ret = !i;
  1286. }
  1287. if (auto visitedObject = frontOrNull(cb->getVisitableObjs(h->visitablePos()))) //we stand on something interesting
  1288. {
  1289. performObjectInteraction (visitedObject, h);
  1290. //BNLOG("Hero %s moved from %s to %s at %s", h->name % startHpos % visitedObject->hoverName % h->visitablePos());
  1291. //throw goalFulfilledException (CGoal(GET_OBJ).setobjid(visitedObject->id));
  1292. }
  1293. if(h) //we could have lost hero after last move
  1294. {
  1295. cb->recalculatePaths();
  1296. if (startHpos == h->visitablePos() && !ret) //we didn't move and didn't reach the target
  1297. {
  1298. throw cannotFulfillGoalException("Invalid path found!");
  1299. }
  1300. }
  1301. logAi->debugStream() << boost::format("Hero %s moved from %s to %s. Returning %d.") % h->name % startHpos % h->visitablePos() % ret;
  1302. return ret;
  1303. }
  1304. void VCAI::tryRealize(Goals::Explore & g)
  1305. {
  1306. throw cannotFulfillGoalException("EXPLORE is not a elementar goal!");
  1307. }
  1308. void VCAI::tryRealize(Goals::RecruitHero & g)
  1309. {
  1310. if(const CGTownInstance *t = findTownWithTavern())
  1311. {
  1312. recruitHero(t, true);
  1313. //TODO try to free way to blocked town
  1314. //TODO: adventure map tavern or prison?
  1315. }
  1316. }
  1317. void VCAI::tryRealize(Goals::VisitTile & g)
  1318. {
  1319. //cb->recalculatePaths();
  1320. if(!g.hero->movement)
  1321. throw cannotFulfillGoalException("Cannot visit tile: hero is out of MPs!");
  1322. if(g.tile == g.hero->visitablePos() && cb->getVisitableObjs(g.hero->visitablePos()).size() < 2)
  1323. {
  1324. logAi->warnStream() << boost::format("Why do I want to move hero %s to tile %s? Already standing on that tile! ")
  1325. % g.hero->name % g.tile;
  1326. throw goalFulfilledException (sptr(g));
  1327. }
  1328. //if(!g.isBlockedBorderGate(g.tile))
  1329. //{
  1330. if (ai->moveHeroToTile(g.tile, g.hero.get()))
  1331. {
  1332. throw goalFulfilledException (sptr(g));
  1333. }
  1334. //}
  1335. //else
  1336. // throw cannotFulfillGoalException("There's a blocked gate!, we should never be here"); //CLEAR_WAY_TO should get keymaster tent
  1337. }
  1338. void VCAI::tryRealize(Goals::VisitHero & g)
  1339. {
  1340. if(!g.hero->movement)
  1341. throw cannotFulfillGoalException("Cannot visit tile: hero is out of MPs!");
  1342. if (ai->moveHeroToTile(g.tile, g.hero.get()))
  1343. {
  1344. throw goalFulfilledException (sptr(g));
  1345. }
  1346. }
  1347. void VCAI::tryRealize(Goals::BuildThis & g)
  1348. {
  1349. const CGTownInstance *t = g.town;
  1350. if(!t && g.hero)
  1351. t = g.hero->visitedTown;
  1352. if(!t)
  1353. {
  1354. for(const CGTownInstance *t : cb->getTownsInfo())
  1355. {
  1356. switch(cb->canBuildStructure(t, BuildingID(g.bid)))
  1357. {
  1358. case EBuildingState::ALLOWED:
  1359. cb->buildBuilding(t, BuildingID(g.bid));
  1360. return;
  1361. default:
  1362. break;
  1363. }
  1364. }
  1365. }
  1366. else if(cb->canBuildStructure(t, BuildingID(g.bid)) == EBuildingState::ALLOWED)
  1367. {
  1368. cb->buildBuilding(t, BuildingID(g.bid));
  1369. return;
  1370. }
  1371. throw cannotFulfillGoalException("Cannot build a given structure!");
  1372. }
  1373. void VCAI::tryRealize(Goals::DigAtTile & g)
  1374. {
  1375. assert(g.hero->visitablePos() == g.tile); //surely we want to crash here?
  1376. if (g.hero->diggingStatus() == CGHeroInstance::CAN_DIG)
  1377. {
  1378. cb->dig(g.hero.get());
  1379. setGoal(g.hero, sptr(Goals::Invalid())); // finished digging
  1380. }
  1381. else
  1382. {
  1383. ai->lockedHeroes[g.hero] = sptr(g); //hero who tries to dig shouldn't do anything else
  1384. throw cannotFulfillGoalException("A hero can't dig!\n");
  1385. }
  1386. }
  1387. void VCAI::tryRealize(Goals::CollectRes & g)
  1388. {
  1389. if(cb->getResourceAmount(static_cast<Res::ERes>(g.resID)) >= g.value)
  1390. throw cannotFulfillGoalException("Goal is already fulfilled!");
  1391. if(const CGObjectInstance *obj = cb->getObj(ObjectInstanceID(g.objid), false))
  1392. {
  1393. if(const IMarket *m = IMarket::castFrom(obj, false))
  1394. {
  1395. for (Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
  1396. {
  1397. if(i == g.resID) continue;
  1398. int toGive, toGet;
  1399. m->getOffer(i, g.resID, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  1400. toGive = toGive * (cb->getResourceAmount(i) / toGive);
  1401. //TODO trade only as much as needed
  1402. cb->trade(obj, EMarketMode::RESOURCE_RESOURCE, i, g.resID, toGive);
  1403. if(cb->getResourceAmount(static_cast<Res::ERes>(g.resID)) >= g.value)
  1404. return;
  1405. }
  1406. throw cannotFulfillGoalException("I cannot get needed resources by trade!");
  1407. }
  1408. else
  1409. {
  1410. throw cannotFulfillGoalException("I don't know how to use this object to raise resources!");
  1411. }
  1412. }
  1413. else
  1414. {
  1415. saving[g.resID] = 1;
  1416. throw cannotFulfillGoalException("No object that could be used to raise resources!");
  1417. }
  1418. }
  1419. void VCAI::tryRealize(Goals::Build & g)
  1420. {
  1421. performTypicalActions(); //TODO: separate build and wander
  1422. throw cannotFulfillGoalException("BUILD has been realized as much as possible.");
  1423. }
  1424. void VCAI::tryRealize(Goals::Invalid & g)
  1425. {
  1426. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1427. }
  1428. void VCAI::tryRealize(Goals::AbstractGoal & g)
  1429. {
  1430. logAi->debugStream() << boost::format("Attempting realizing goal with code %s") % g.name();
  1431. throw cannotFulfillGoalException("Unknown type of goal !");
  1432. }
  1433. const CGTownInstance * VCAI::findTownWithTavern() const
  1434. {
  1435. for(const CGTownInstance *t : cb->getTownsInfo())
  1436. if(t->hasBuilt(BuildingID::TAVERN) && !t->visitingHero)
  1437. return t;
  1438. return nullptr;
  1439. }
  1440. std::vector<HeroPtr> VCAI::getUnblockedHeroes() const
  1441. {
  1442. std::vector<HeroPtr> ret;
  1443. boost::copy(cb->getHeroesInfo(), std::back_inserter(ret));
  1444. for(auto h : lockedHeroes)
  1445. {
  1446. //if (!h.second.invalid()) //we can use heroes without valid goal
  1447. 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
  1448. erase_if_present(ret, h.first);
  1449. }
  1450. return ret;
  1451. }
  1452. HeroPtr VCAI::primaryHero() const
  1453. {
  1454. auto hs = cb->getHeroesInfo();
  1455. boost::sort(hs, compareHeroStrength);
  1456. if(hs.empty())
  1457. return nullptr;
  1458. return hs.back();
  1459. }
  1460. void VCAI::endTurn()
  1461. {
  1462. logAi->debugStream() << "Player " << static_cast<int>(playerID.getNum()) << " ends turn";
  1463. if(!status.haveTurn())
  1464. {
  1465. logAi->errorStream() << "Not having turn at the end of turn???";
  1466. }
  1467. do
  1468. {
  1469. cb->endTurn();
  1470. } 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
  1471. logAi->debugStream() << "Player " << static_cast<int>(playerID.getNum()) << " ended turn";
  1472. }
  1473. void VCAI::striveToGoal(Goals::TSubgoal ultimateGoal)
  1474. {
  1475. if (ultimateGoal->invalid())
  1476. return;
  1477. //we are looking for abstract goals
  1478. auto abstractGoal = striveToGoalInternal (ultimateGoal, false);
  1479. if (abstractGoal->invalid())
  1480. return;
  1481. //we received abstratc goal, need to find concrete goals
  1482. striveToGoalInternal (abstractGoal, true);
  1483. //TODO: save abstract goals not related to hero
  1484. }
  1485. Goals::TSubgoal VCAI::striveToGoalInternal(Goals::TSubgoal ultimateGoal, bool onlyAbstract)
  1486. {
  1487. Goals::TSubgoal abstractGoal = sptr(Goals::Invalid());
  1488. while(1)
  1489. {
  1490. Goals::TSubgoal goal = ultimateGoal;
  1491. logAi->debugStream() << boost::format("Striving to goal of type %s") % ultimateGoal->name();
  1492. int maxGoals = 100; //preventing deadlock for mutually dependent goals
  1493. //FIXME: do not try to realize goal when loop didn't suceed
  1494. while(!goal->isElementar && maxGoals && (onlyAbstract || !goal->isAbstract))
  1495. {
  1496. logAi->debugStream() << boost::format("Considering goal %s") % goal->name();
  1497. try
  1498. {
  1499. boost::this_thread::interruption_point();
  1500. goal = goal->whatToDoToAchieve();
  1501. --maxGoals;
  1502. }
  1503. catch(std::exception &e)
  1504. {
  1505. logAi->debugStream() << boost::format("Goal %s decomposition failed: %s") % goal->name() % e.what();
  1506. //setGoal (goal.hero, INVALID); //test: if we don't know how to realize goal, we should abandon it for now
  1507. return sptr(Goals::Invalid());
  1508. }
  1509. }
  1510. try
  1511. {
  1512. boost::this_thread::interruption_point();
  1513. if (!maxGoals)
  1514. {
  1515. std::runtime_error e("Too many subgoals, don't know what to do");
  1516. throw (e);
  1517. }
  1518. if (goal->hero) //lock this hero to fulfill ultimate goal
  1519. {
  1520. if (maxGoals)
  1521. {
  1522. setGoal(goal->hero, goal);
  1523. }
  1524. else
  1525. {
  1526. setGoal(goal->hero, sptr(Goals::Invalid())); // we seemingly don't know what to do with hero
  1527. }
  1528. }
  1529. if (goal->isAbstract)
  1530. {
  1531. abstractGoal = goal; //allow only one abstract goal per call
  1532. logAi->debugStream() << boost::format("Choosing abstract goal %s") % goal->name();
  1533. break;
  1534. }
  1535. else
  1536. goal->accept(this);
  1537. boost::this_thread::interruption_point();
  1538. }
  1539. catch(boost::thread_interrupted &e)
  1540. {
  1541. logAi->debugStream() << boost::format("Player %d: Making turn thread received an interruption!") % playerID;
  1542. throw; //rethrow, we want to truly end this thread
  1543. }
  1544. catch(goalFulfilledException &e)
  1545. {
  1546. completeGoal (goal);
  1547. if (ultimateGoal->fulfillsMe(goal) || maxGoals > 98) //completed goal was main goal //TODO: find better condition
  1548. return sptr(Goals::Invalid());
  1549. }
  1550. catch(std::exception &e)
  1551. {
  1552. logAi->debugStream() << boost::format("Failed to realize subgoal of type %s (greater goal type was %s), I will stop.") % goal->name() % ultimateGoal->name();
  1553. logAi->debugStream() << boost::format("The error message was: %s") % e.what();
  1554. break;
  1555. }
  1556. }
  1557. return abstractGoal;
  1558. }
  1559. void VCAI::striveToQuest (const QuestInfo &q)
  1560. {
  1561. if (q.quest->missionType && q.quest->progress != CQuest::COMPLETE) //FIXME: quests are never synchronized. Pointer handling needed
  1562. {
  1563. MetaString ms;
  1564. q.quest->getRolloverText(ms, false);
  1565. logAi->debugStream() << boost::format("Trying to realize quest: %s") % ms.toString();
  1566. auto heroes = cb->getHeroesInfo();
  1567. switch (q.quest->missionType)
  1568. {
  1569. case CQuest::MISSION_ART:
  1570. {
  1571. for (auto hero : heroes) //TODO: remove duplicated code?
  1572. {
  1573. if (q.quest->checkQuest(hero))
  1574. {
  1575. striveToGoal (sptr(Goals::GetObj(q.obj->id.getNum()).sethero(hero)));
  1576. return;
  1577. }
  1578. }
  1579. for (auto art : q.quest->m5arts)
  1580. {
  1581. striveToGoal (sptr(Goals::GetArtOfType(art))); //TODO: transport?
  1582. }
  1583. break;
  1584. }
  1585. case CQuest::MISSION_HERO:
  1586. {
  1587. //striveToGoal (CGoal(RECRUIT_HERO));
  1588. for (auto hero : heroes)
  1589. {
  1590. if (q.quest->checkQuest(hero))
  1591. {
  1592. striveToGoal (sptr(Goals::GetObj(q.obj->id.getNum()).sethero(hero)));
  1593. return;
  1594. }
  1595. }
  1596. striveToGoal (sptr(Goals::FindObj(Obj::PRISON))); //rule of a thumb - quest heroes usually are locked in prisons
  1597. //BNLOG ("Don't know how to recruit hero with id %d\n", q.quest->m13489val);
  1598. break;
  1599. }
  1600. case CQuest::MISSION_ARMY:
  1601. {
  1602. for (auto hero : heroes)
  1603. {
  1604. if (q.quest->checkQuest(hero)) //veyr bad info - stacks can be split between multiple heroes :(
  1605. {
  1606. striveToGoal (sptr(Goals::GetObj(q.obj->id.getNum()).sethero(hero)));
  1607. return;
  1608. }
  1609. }
  1610. for (auto creature : q.quest->m6creatures)
  1611. {
  1612. striveToGoal (sptr(Goals::GatherTroops(creature.type->idNumber, creature.count)));
  1613. }
  1614. //TODO: exchange armies... oh my
  1615. //BNLOG ("Don't know how to recruit %d of %s\n", (int)(creature.count) % creature.type->namePl);
  1616. break;
  1617. }
  1618. case CQuest::MISSION_RESOURCES:
  1619. {
  1620. if (heroes.size())
  1621. {
  1622. if (q.quest->checkQuest(heroes.front())) //it doesn't matter which hero it is
  1623. {
  1624. striveToGoal (sptr(Goals::VisitTile(q.tile)));
  1625. }
  1626. else
  1627. {
  1628. for (int i = 0; i < q.quest->m7resources.size(); ++i)
  1629. {
  1630. if (q.quest->m7resources[i])
  1631. striveToGoal (sptr(Goals::CollectRes(i, q.quest->m7resources[i])));
  1632. }
  1633. }
  1634. }
  1635. else
  1636. striveToGoal (sptr(Goals::RecruitHero())); //FIXME: checkQuest requires any hero belonging to player :(
  1637. break;
  1638. }
  1639. case CQuest::MISSION_KILL_HERO:
  1640. case CQuest::MISSION_KILL_CREATURE:
  1641. {
  1642. auto obj = cb->getObjByQuestIdentifier(q.quest->m13489val);
  1643. if (obj)
  1644. striveToGoal (sptr(Goals::GetObj(obj->id.getNum())));
  1645. else
  1646. striveToGoal (sptr(Goals::VisitTile(q.tile))); //visit seer hut
  1647. break;
  1648. }
  1649. case CQuest::MISSION_PRIMARY_STAT:
  1650. {
  1651. auto heroes = cb->getHeroesInfo();
  1652. for (auto hero : heroes)
  1653. {
  1654. if (q.quest->checkQuest(hero))
  1655. {
  1656. striveToGoal (sptr(Goals::GetObj(q.obj->id.getNum()).sethero(hero)));
  1657. return;
  1658. }
  1659. }
  1660. for (int i = 0; i < q.quest->m2stats.size(); ++i)
  1661. {
  1662. logAi->debugStream() << boost::format("Don't know how to increase primary stat %d") % i;
  1663. }
  1664. break;
  1665. }
  1666. case CQuest::MISSION_LEVEL:
  1667. {
  1668. auto heroes = cb->getHeroesInfo();
  1669. for (auto hero : heroes)
  1670. {
  1671. if (q.quest->checkQuest(hero))
  1672. {
  1673. striveToGoal (sptr(Goals::VisitTile(q.tile).sethero(hero))); //TODO: causes infinite loop :/
  1674. return;
  1675. }
  1676. }
  1677. logAi->debugStream() << boost::format("Don't know how to reach hero level %d") % q.quest->m13489val;
  1678. break;
  1679. }
  1680. case CQuest::MISSION_PLAYER:
  1681. {
  1682. if (playerID.getNum() != q.quest->m13489val)
  1683. logAi->debugStream() << boost::format("Can't be player of color %d") % q.quest->m13489val;
  1684. break;
  1685. }
  1686. case CQuest::MISSION_KEYMASTER:
  1687. {
  1688. striveToGoal (sptr(Goals::FindObj(Obj::KEYMASTER, q.obj->subID)));
  1689. break;
  1690. }
  1691. }
  1692. }
  1693. }
  1694. void VCAI::performTypicalActions()
  1695. {
  1696. for(const CGTownInstance *t : cb->getTownsInfo())
  1697. {
  1698. logAi->debugStream() << boost::format("Looking into %s") % t->name;
  1699. buildStructure(t);
  1700. buildArmyIn(t);
  1701. if(!ai->primaryHero() ||
  1702. (t->getArmyStrength() > ai->primaryHero()->getArmyStrength() * 2 && !isAccessibleForHero(t->visitablePos(), ai->primaryHero())))
  1703. {
  1704. recruitHero(t);
  1705. buildArmyIn(t);
  1706. }
  1707. }
  1708. for(auto h : getUnblockedHeroes())
  1709. {
  1710. logAi->debugStream() << boost::format("Looking into %s, MP=%d") % h->name.c_str() % h->movement;
  1711. makePossibleUpgrades(*h);
  1712. cb->setSelection(*h);
  1713. try
  1714. {
  1715. wander(h);
  1716. }
  1717. catch(std::exception &e)
  1718. {
  1719. logAi->debugStream() << boost::format("Cannot use this hero anymore, received exception: %s") % e.what();
  1720. continue;
  1721. }
  1722. }
  1723. }
  1724. void VCAI::buildArmyIn(const CGTownInstance * t)
  1725. {
  1726. makePossibleUpgrades(t->visitingHero);
  1727. makePossibleUpgrades(t);
  1728. recruitCreatures(t);
  1729. moveCreaturesToHero(t);
  1730. }
  1731. int3 VCAI::explorationBestNeighbour(int3 hpos, int radius, HeroPtr h)
  1732. {
  1733. TimeCheck tc("looking for best exploration neighbour");
  1734. std::map<int3, int> dstToRevealedTiles;
  1735. for(crint3 dir : dirs)
  1736. if(cb->isInTheMap(hpos+dir))
  1737. dstToRevealedTiles[hpos + dir] = howManyTilesWillBeDiscovered(radius, hpos, dir) * isSafeToVisit(h, hpos + dir);
  1738. auto best = dstToRevealedTiles.begin();
  1739. best->second *= cb->getPathInfo(best->first)->reachable();
  1740. best->second *= cb->getPathInfo(best->first)->accessible == CGPathNode::ACCESSIBLE;
  1741. for(auto i = dstToRevealedTiles.begin(); i != dstToRevealedTiles.end(); i++)
  1742. {
  1743. const CGPathNode *pn = cb->getPathInfo(i->first);
  1744. //const TerrainTile *t = cb->getTile(i->first);
  1745. if(best->second < i->second && i->second && pn->reachable() && pn->accessible == CGPathNode::ACCESSIBLE)
  1746. best = i;
  1747. }
  1748. if(best->second)
  1749. return best->first;
  1750. throw cannotFulfillGoalException("No neighbour will bring new discoveries!");
  1751. }
  1752. int3 VCAI::explorationNewPoint(int radius, HeroPtr h, std::vector<std::vector<int3> > &tiles)
  1753. {
  1754. TimeCheck tc("looking for new exploration point");
  1755. logAi->debugStream() << "Looking for an another place for exploration...";
  1756. tiles.resize(radius);
  1757. foreach_tile_pos([&](const int3 &pos)
  1758. {
  1759. if(!cb->isVisible(pos))
  1760. tiles[0].push_back(pos);
  1761. });
  1762. for (int i = 1; i < radius; i++)
  1763. {
  1764. getVisibleNeighbours(tiles[i-1], tiles[i]);
  1765. removeDuplicates(tiles[i]);
  1766. for(const int3 &tile : tiles[i])
  1767. {
  1768. if(cb->getPathInfo(tile)->reachable() && isSafeToVisit(h, tile) && howManyTilesWillBeDiscovered(tile, radius) && !isBlockedBorderGate(tile))
  1769. {
  1770. return tile;
  1771. }
  1772. }
  1773. }
  1774. throw cannotFulfillGoalException("No accessible tile will bring discoveries!");
  1775. }
  1776. TResources VCAI::estimateIncome() const
  1777. {
  1778. TResources ret;
  1779. for(const CGTownInstance *t : cb->getTownsInfo())
  1780. {
  1781. ret[Res::GOLD] += t->dailyIncome();
  1782. //TODO duplikuje newturn
  1783. if(t->hasBuilt(BuildingID::RESOURCE_SILO)) //there is resource silo
  1784. {
  1785. if(t->town->primaryRes == Res::WOOD_AND_ORE) //we'll give wood and ore
  1786. {
  1787. ret[Res::WOOD] ++;
  1788. ret[Res::ORE] ++;
  1789. }
  1790. else
  1791. {
  1792. ret[t->town->primaryRes] ++;
  1793. }
  1794. }
  1795. }
  1796. for(const CGObjectInstance *obj : getFlaggedObjects())
  1797. {
  1798. if(obj->ID == Obj::MINE)
  1799. {
  1800. switch(obj->subID)
  1801. {
  1802. case Res::WOOD:
  1803. case Res::ORE:
  1804. ret[obj->subID] += WOOD_ORE_MINE_PRODUCTION;
  1805. break;
  1806. case Res::GOLD:
  1807. case 7: //abandoned mine -> also gold
  1808. ret[Res::GOLD] += GOLD_MINE_PRODUCTION;
  1809. break;
  1810. default:
  1811. ret[obj->subID] += RESOURCE_MINE_PRODUCTION;
  1812. break;
  1813. }
  1814. }
  1815. }
  1816. return ret;
  1817. }
  1818. bool VCAI::containsSavedRes(const TResources &cost) const
  1819. {
  1820. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  1821. {
  1822. if(saving[i] && cost[i])
  1823. return true;
  1824. }
  1825. return false;
  1826. }
  1827. void VCAI::checkHeroArmy (HeroPtr h)
  1828. {
  1829. auto it = lockedHeroes.find(h);
  1830. if (it != lockedHeroes.end())
  1831. {
  1832. if (it->second->goalType == Goals::GATHER_ARMY && it->second->value <= h->getArmyStrength())
  1833. completeGoal(sptr(Goals::GatherArmy(it->second->value).sethero(h)));
  1834. }
  1835. }
  1836. void VCAI::recruitHero(const CGTownInstance * t, bool throwing)
  1837. {
  1838. logAi->debugStream() << boost::format("Trying to recruit a hero in %s at %s") % t->name % t->visitablePos();
  1839. if(auto availableHero = frontOrNull(cb->getAvailableHeroes(t)))
  1840. cb->recruitHero(t, availableHero);
  1841. else if(throwing)
  1842. throw cannotFulfillGoalException("No available heroes in tavern in " + t->nodeName());
  1843. }
  1844. void VCAI::finish()
  1845. {
  1846. if(makingTurn)
  1847. makingTurn->interrupt();
  1848. }
  1849. void VCAI::requestActionASAP(std::function<void()> whatToDo)
  1850. {
  1851. // static boost::mutex m;
  1852. // boost::unique_lock<boost::mutex> mylock(m);
  1853. boost::barrier b(2);
  1854. boost::thread newThread([&b,this,whatToDo]()
  1855. {
  1856. setThreadName("VCAI::requestActionASAP::helper");
  1857. SET_GLOBAL_STATE(this);
  1858. boost::shared_lock<boost::shared_mutex> gsLock(cb->getGsMutex());
  1859. b.wait();
  1860. whatToDo();
  1861. });
  1862. b.wait();
  1863. }
  1864. void VCAI::lostHero(HeroPtr h)
  1865. {
  1866. logAi->debugStream() << boost::format("I lost my hero %s. It's best to forget and move on.") % h.name;
  1867. erase_if_present(lockedHeroes, h);
  1868. for(auto obj : reservedHeroesMap[h])
  1869. {
  1870. erase_if_present(reservedObjs, obj); //unreserve all objects for that hero
  1871. }
  1872. erase_if_present(reservedHeroesMap, h);
  1873. }
  1874. void VCAI::answerQuery(QueryID queryID, int selection)
  1875. {
  1876. logAi->debugStream() << boost::format("I'll answer the query %d giving the choice %d") % queryID % selection;
  1877. if(queryID != QueryID(-1))
  1878. {
  1879. cb->selectionMade(selection, queryID);
  1880. }
  1881. else
  1882. {
  1883. logAi->debugStream() << boost::format("Since the query ID is %d, the answer won't be sent. This is not a real query!") % queryID;
  1884. //do nothing
  1885. }
  1886. }
  1887. void VCAI::requestSent(const CPackForServer *pack, int requestID)
  1888. {
  1889. //BNLOG("I have sent request of type %s", typeid(*pack).name());
  1890. if(auto reply = dynamic_cast<const QueryReply*>(pack))
  1891. {
  1892. status.attemptedAnsweringQuery(reply->qid, requestID);
  1893. }
  1894. }
  1895. std::string VCAI::getBattleAIName() const
  1896. {
  1897. if(settings["server"]["neutralAI"].getType() == JsonNode::DATA_STRING)
  1898. return settings["server"]["neutralAI"].String();
  1899. else
  1900. return "StupidAI";
  1901. }
  1902. void VCAI::validateObject(const CGObjectInstance *obj)
  1903. {
  1904. validateObject(obj->id);
  1905. }
  1906. void VCAI::validateObject(ObjectIdRef obj)
  1907. {
  1908. auto matchesId = [&] (const CGObjectInstance *hlpObj) -> bool { return hlpObj->id == obj.id; };
  1909. if(!obj)
  1910. {
  1911. erase_if(visitableObjs, matchesId);
  1912. for(auto &p : reservedHeroesMap)
  1913. erase_if(p.second, matchesId);
  1914. erase_if(reservedObjs, matchesId);
  1915. }
  1916. }
  1917. TResources VCAI::freeResources() const
  1918. {
  1919. TResources myRes = cb->getResourceAmount();
  1920. myRes[Res::GOLD] -= GOLD_RESERVE;
  1921. vstd::amax(myRes[Res::GOLD], 0);
  1922. return myRes;
  1923. }
  1924. AIStatus::AIStatus()
  1925. {
  1926. battle = NO_BATTLE;
  1927. havingTurn = false;
  1928. ongoingHeroMovement = false;
  1929. }
  1930. AIStatus::~AIStatus()
  1931. {
  1932. }
  1933. void AIStatus::setBattle(BattleState BS)
  1934. {
  1935. boost::unique_lock<boost::mutex> lock(mx);
  1936. LOG_TRACE_PARAMS(logAi, "battle state=%d", (int)BS);
  1937. battle = BS;
  1938. cv.notify_all();
  1939. }
  1940. BattleState AIStatus::getBattle()
  1941. {
  1942. boost::unique_lock<boost::mutex> lock(mx);
  1943. return battle;
  1944. }
  1945. void AIStatus::addQuery(QueryID ID, std::string description)
  1946. {
  1947. boost::unique_lock<boost::mutex> lock(mx);
  1948. if(ID == QueryID(-1))
  1949. {
  1950. logAi->debugStream() << boost::format("The \"query\" has an id %d, it'll be ignored as non-query. Description: %s") % ID % description;
  1951. return;
  1952. }
  1953. assert(!vstd::contains(remainingQueries, ID));
  1954. assert(ID.getNum() >= 0);
  1955. remainingQueries[ID] = description;
  1956. cv.notify_all();
  1957. logAi->debugStream() << boost::format("Adding query %d - %s. Total queries count: %d") % ID % description % remainingQueries.size();
  1958. }
  1959. void AIStatus::removeQuery(QueryID ID)
  1960. {
  1961. boost::unique_lock<boost::mutex> lock(mx);
  1962. assert(vstd::contains(remainingQueries, ID));
  1963. std::string description = remainingQueries[ID];
  1964. remainingQueries.erase(ID);
  1965. cv.notify_all();
  1966. logAi->debugStream() << boost::format("Removing query %d - %s. Total queries count: %d") % ID % description % remainingQueries.size();
  1967. }
  1968. int AIStatus::getQueriesCount()
  1969. {
  1970. boost::unique_lock<boost::mutex> lock(mx);
  1971. return remainingQueries.size();
  1972. }
  1973. void AIStatus::startedTurn()
  1974. {
  1975. boost::unique_lock<boost::mutex> lock(mx);
  1976. havingTurn = true;
  1977. cv.notify_all();
  1978. }
  1979. void AIStatus::madeTurn()
  1980. {
  1981. boost::unique_lock<boost::mutex> lock(mx);
  1982. havingTurn = false;
  1983. cv.notify_all();
  1984. }
  1985. void AIStatus::waitTillFree()
  1986. {
  1987. boost::unique_lock<boost::mutex> lock(mx);
  1988. while(battle != NO_BATTLE || !remainingQueries.empty() || !objectsBeingVisited.empty() || ongoingHeroMovement)
  1989. cv.timed_wait(lock, boost::posix_time::milliseconds(100));
  1990. }
  1991. bool AIStatus::haveTurn()
  1992. {
  1993. boost::unique_lock<boost::mutex> lock(mx);
  1994. return havingTurn;
  1995. }
  1996. void AIStatus::attemptedAnsweringQuery(QueryID queryID, int answerRequestID)
  1997. {
  1998. boost::unique_lock<boost::mutex> lock(mx);
  1999. assert(vstd::contains(remainingQueries, queryID));
  2000. std::string description = remainingQueries[queryID];
  2001. logAi->debugStream() << boost::format("Attempted answering query %d - %s. Request id=%d. Waiting for results...") % queryID % description % answerRequestID;
  2002. requestToQueryID[answerRequestID] = queryID;
  2003. }
  2004. void AIStatus::receivedAnswerConfirmation(int answerRequestID, int result)
  2005. {
  2006. assert(vstd::contains(requestToQueryID, answerRequestID));
  2007. QueryID query = requestToQueryID[answerRequestID];
  2008. assert(vstd::contains(remainingQueries, query));
  2009. requestToQueryID.erase(answerRequestID);
  2010. if(result)
  2011. {
  2012. removeQuery(query);
  2013. }
  2014. else
  2015. {
  2016. logAi->errorStream() << "Something went really wrong, failed to answer query " << query << ": " << remainingQueries[query];
  2017. //TODO safely retry
  2018. }
  2019. }
  2020. void AIStatus::heroVisit(const CGObjectInstance *obj, bool started)
  2021. {
  2022. boost::unique_lock<boost::mutex> lock(mx);
  2023. if(started)
  2024. objectsBeingVisited.push_back(obj);
  2025. else
  2026. {
  2027. // There can be more than one object visited at the time (eg. hero visits Subterranean Gate
  2028. // causing visit to hero on the other side.
  2029. // However, we are guaranteed that start/end visit notification maintain stack order.
  2030. assert(!objectsBeingVisited.empty());
  2031. objectsBeingVisited.pop_back();
  2032. }
  2033. cv.notify_all();
  2034. }
  2035. void AIStatus::setMove(bool ongoing)
  2036. {
  2037. boost::unique_lock<boost::mutex> lock(mx);
  2038. ongoingHeroMovement = ongoing;
  2039. cv.notify_all();
  2040. }
  2041. SectorMap::SectorMap()
  2042. {
  2043. // int3 sizes = cb->getMapSize();
  2044. // sector.resize(sizes.x);
  2045. // for(auto &i : sector)
  2046. // i.resize(sizes.y);
  2047. //
  2048. // for(auto &i : sector)
  2049. // for(auto &j : i)
  2050. // j.resize(sizes.z, 0);
  2051. update();
  2052. }
  2053. bool markIfBlocked(ui8 &sec, crint3 pos, const TerrainTile *t)
  2054. {
  2055. if(t->blocked && !t->visitable)
  2056. {
  2057. sec = NOT_AVAILABLE;
  2058. return true;
  2059. }
  2060. return false;
  2061. }
  2062. bool markIfBlocked(ui8 &sec, crint3 pos)
  2063. {
  2064. return markIfBlocked(sec, pos, cb->getTile(pos));
  2065. }
  2066. void SectorMap::update()
  2067. {
  2068. clear();
  2069. int curSector = 3; //0 is invisible, 1 is not explored
  2070. foreach_tile_pos([&](crint3 pos)
  2071. {
  2072. if(retreiveTile(pos) == NOT_CHECKED)
  2073. {
  2074. if(!markIfBlocked(retreiveTile(pos), pos))
  2075. exploreNewSector(pos, curSector++);
  2076. }
  2077. });
  2078. valid = true;
  2079. }
  2080. void SectorMap::clear()
  2081. {
  2082. sector = cb->getVisibilityMap();
  2083. valid = false;
  2084. }
  2085. void SectorMap::exploreNewSector(crint3 pos, int num)
  2086. {
  2087. Sector &s = infoOnSectors[num];
  2088. s.id = num;
  2089. s.water = cb->getTile(pos)->isWater();
  2090. std::queue<int3> toVisit;
  2091. toVisit.push(pos);
  2092. while(!toVisit.empty())
  2093. {
  2094. int3 curPos = toVisit.front();
  2095. toVisit.pop();
  2096. ui8 &sec = retreiveTile(curPos);
  2097. if(sec == NOT_CHECKED)
  2098. {
  2099. const TerrainTile *t = cb->getTile(curPos);
  2100. if(!markIfBlocked(sec, curPos, t))
  2101. {
  2102. if(t->isWater() == s.water) //sector is only-water or only-land
  2103. {
  2104. sec = num;
  2105. s.tiles.push_back(curPos);
  2106. foreach_neighbour(curPos, [&](crint3 neighPos)
  2107. {
  2108. if(retreiveTile(neighPos) == NOT_CHECKED)
  2109. {
  2110. toVisit.push(neighPos);
  2111. //parent[neighPos] = curPos;
  2112. }
  2113. const TerrainTile *nt = cb->getTile(neighPos, false);
  2114. if(nt && nt->isWater() != s.water && canBeEmbarkmentPoint(nt))
  2115. {
  2116. s.embarkmentPoints.push_back(neighPos);
  2117. }
  2118. });
  2119. if(t->visitable && vstd::contains(ai->knownSubterraneanGates, t->visitableObjects.front()))
  2120. toVisit.push(ai->knownSubterraneanGates[t->visitableObjects.front()]->visitablePos());
  2121. }
  2122. }
  2123. }
  2124. }
  2125. removeDuplicates(s.embarkmentPoints);
  2126. }
  2127. void SectorMap::write(crstring fname)
  2128. {
  2129. std::ofstream out(fname);
  2130. for(int k = 0; k < cb->getMapSize().z; k++)
  2131. {
  2132. for(int j = 0; j < cb->getMapSize().y; j++)
  2133. {
  2134. for(int i = 0; i < cb->getMapSize().x; i++)
  2135. {
  2136. out << (int)sector[i][j][k] << '\t';
  2137. }
  2138. out << std::endl;
  2139. }
  2140. out << std::endl;
  2141. }
  2142. }
  2143. bool isWeeklyRevisitable (const CGObjectInstance * obj)
  2144. { //TODO: allow polling of remaining creatures in dwelling
  2145. if (dynamic_cast<const CGVisitableOPW *>(obj) || //ensures future compatibility, unlike IDs
  2146. dynamic_cast<const CGDwelling *>(obj) ||
  2147. dynamic_cast<const CBank *>(obj)) //banks tend to respawn often in mods
  2148. return true;
  2149. switch (obj->ID)
  2150. {
  2151. case Obj::STABLES:
  2152. case Obj::MAGIC_WELL:
  2153. case Obj::HILL_FORT:
  2154. return true;
  2155. case Obj::BORDER_GATE:
  2156. case Obj::BORDERGUARD:
  2157. return (dynamic_cast <const CGKeys *>(obj))->wasMyColorVisited (ai->playerID); //FIXME: they could be revisited sooner than in a week
  2158. }
  2159. return false;
  2160. }
  2161. bool shouldVisit(HeroPtr h, const CGObjectInstance * obj)
  2162. {
  2163. switch (obj->ID)
  2164. {
  2165. case Obj::BORDERGUARD:
  2166. case Obj::BORDER_GATE:
  2167. {
  2168. for (auto q : ai->myCb->getMyQuests())
  2169. {
  2170. if (q.obj == obj)
  2171. {
  2172. return false; // do not visit guards or gates when wandering
  2173. }
  2174. }
  2175. return true; //we don't have this quest yet
  2176. }
  2177. case Obj::SEER_HUT:
  2178. case Obj::QUEST_GUARD:
  2179. {
  2180. for (auto q : ai->myCb->getMyQuests())
  2181. {
  2182. if (q.obj == obj)
  2183. {
  2184. if (q.quest->checkQuest(*h))
  2185. return true; //we completed the quest
  2186. else
  2187. return false; //we can't complete this quest
  2188. }
  2189. }
  2190. return true; //we don't have this quest yet
  2191. }
  2192. case Obj::CREATURE_GENERATOR1:
  2193. {
  2194. if (obj->tempOwner != h->tempOwner)
  2195. return true; //flag just in case
  2196. bool canRecruitCreatures = false;
  2197. const CGDwelling * d = dynamic_cast<const CGDwelling *>(obj);
  2198. for(auto level : d->creatures)
  2199. {
  2200. for(auto c : level.second)
  2201. {
  2202. if (h->getSlotFor(CreatureID(c)) != SlotID())
  2203. canRecruitCreatures = true;
  2204. }
  2205. }
  2206. return canRecruitCreatures;
  2207. }
  2208. case Obj::HILL_FORT:
  2209. {
  2210. for (auto slot : h->Slots())
  2211. {
  2212. if (slot.second->type->upgrades.size())
  2213. return true; //TODO: check price?
  2214. }
  2215. return false;
  2216. }
  2217. case Obj::MONOLITH1:
  2218. case Obj::MONOLITH2:
  2219. case Obj::MONOLITH3:
  2220. case Obj::WHIRLPOOL:
  2221. //TODO: mechanism for handling monoliths
  2222. return false;
  2223. case Obj::SCHOOL_OF_MAGIC:
  2224. case Obj::SCHOOL_OF_WAR:
  2225. {
  2226. TResources myRes = ai->myCb->getResourceAmount();
  2227. if (myRes[Res::GOLD] - GOLD_RESERVE < 1000)
  2228. return false;
  2229. }
  2230. break;
  2231. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2232. if (h->level < 12)
  2233. return false;
  2234. break;
  2235. case Obj::TREE_OF_KNOWLEDGE:
  2236. {
  2237. TResources myRes = ai->myCb->getResourceAmount();
  2238. if (myRes[Res::GOLD] - GOLD_RESERVE < 2000 || myRes[Res::GEMS] < 10)
  2239. return false;
  2240. }
  2241. break;
  2242. case Obj::MAGIC_WELL:
  2243. return h->mana < h->manaLimit();
  2244. case Obj::PRISON:
  2245. return ai->myCb->getHeroesInfo().size() < GameConstants::MAX_HEROES_PER_PLAYER;
  2246. case Obj::BOAT:
  2247. return false;
  2248. //Boats are handled by pathfinder
  2249. }
  2250. if (obj->wasVisited(*h)) //it must pointer to hero instance, heroPtr calls function wasVisited(ui8 player);
  2251. return false;
  2252. return true;
  2253. }
  2254. int3 SectorMap::firstTileToGet(HeroPtr h, crint3 dst)
  2255. {
  2256. int sourceSector = retreiveTile(h->visitablePos()),
  2257. destinationSector = retreiveTile(dst);
  2258. if(sourceSector != destinationSector)
  2259. {
  2260. const Sector *src = &infoOnSectors[sourceSector],
  2261. *dst = &infoOnSectors[destinationSector];
  2262. std::map<const Sector*, const Sector*> preds;
  2263. std::queue<const Sector *> sq;
  2264. sq.push(src);
  2265. while(!sq.empty())
  2266. {
  2267. const Sector *s = sq.front();
  2268. sq.pop();
  2269. for(int3 ep : s->embarkmentPoints)
  2270. {
  2271. Sector *neigh = &infoOnSectors[retreiveTile(ep)];
  2272. //preds[s].push_back(neigh);
  2273. if(!preds[neigh])
  2274. {
  2275. preds[neigh] = s;
  2276. sq.push(neigh);
  2277. }
  2278. }
  2279. //TODO consider other types of connections between sectors?
  2280. }
  2281. if(!preds[dst])
  2282. {
  2283. write("test.txt");
  2284. ai->completeGoal (sptr(Goals::Explore(h))); //if we can't find the way, seemingly all tiles were explored
  2285. //TODO: more organized way?
  2286. throw cannotFulfillGoalException(boost::str(boost::format("Cannot find connection between sectors %d and %d") % src->id % dst->id));
  2287. }
  2288. std::vector<const Sector*> toTraverse;
  2289. toTraverse.push_back(dst);
  2290. while(toTraverse.back() != src)
  2291. {
  2292. toTraverse.push_back(preds[toTraverse.back()]);
  2293. }
  2294. if(preds[dst])
  2295. {
  2296. const Sector *sectorToReach = toTraverse.at(toTraverse.size() - 2);
  2297. if(!src->water && sectorToReach->water) //embark
  2298. {
  2299. //embark on ship -> look for an EP with a boat
  2300. auto firstEP = boost::find_if(src->embarkmentPoints, [=](crint3 pos) -> bool
  2301. {
  2302. const TerrainTile *t = cb->getTile(pos);
  2303. return t && t->visitableObjects.size() == 1 && t->topVisitableId() == Obj::BOAT
  2304. && retreiveTile(pos) == sectorToReach->id;
  2305. });
  2306. if(firstEP != src->embarkmentPoints.end())
  2307. {
  2308. return *firstEP;
  2309. }
  2310. else
  2311. {
  2312. //we need to find a shipyard with an access to the desired sector's EP
  2313. //TODO what about Summon Boat spell?
  2314. std::vector<const IShipyard *> shipyards;
  2315. for(const CGTownInstance *t : cb->getTownsInfo())
  2316. {
  2317. if(t->hasBuilt(BuildingID::SHIPYARD))
  2318. shipyards.push_back(t);
  2319. }
  2320. std::vector<const CGObjectInstance*> visObjs;
  2321. ai->retreiveVisitableObjs(visObjs, true);
  2322. for(const CGObjectInstance *obj : visObjs)
  2323. {
  2324. if(obj->ID != Obj::TOWN) //towns were handled in the previous loop
  2325. if(const IShipyard *shipyard = IShipyard::castFrom(obj))
  2326. shipyards.push_back(shipyard);
  2327. }
  2328. shipyards.erase(boost::remove_if(shipyards, [=](const IShipyard *shipyard) -> bool
  2329. {
  2330. return shipyard->shipyardStatus() != 0 || retreiveTile(shipyard->bestLocation()) != sectorToReach->id;
  2331. }),shipyards.end());
  2332. if(!shipyards.size())
  2333. {
  2334. //TODO consider possibility of building shipyard in a town
  2335. throw cannotFulfillGoalException("There is no known shipyard!");
  2336. }
  2337. //we have only shipyards that possibly can build ships onto the appropriate EP
  2338. auto ownedGoodShipyard = boost::find_if(shipyards, [](const IShipyard *s) -> bool
  2339. {
  2340. return s->o->tempOwner == ai->playerID;
  2341. });
  2342. if(ownedGoodShipyard != shipyards.end())
  2343. {
  2344. const IShipyard *s = *ownedGoodShipyard;
  2345. TResources shipCost;
  2346. s->getBoatCost(shipCost);
  2347. if(cb->getResourceAmount().canAfford(shipCost))
  2348. {
  2349. int3 ret = s->bestLocation();
  2350. cb->buildBoat(s);
  2351. return ret;
  2352. }
  2353. else
  2354. {
  2355. //TODO gather res
  2356. throw cannotFulfillGoalException("Not enough resources to build a boat");
  2357. }
  2358. }
  2359. else
  2360. {
  2361. //TODO pick best shipyard to take over
  2362. return shipyards.front()->o->visitablePos();
  2363. }
  2364. }
  2365. }
  2366. else if(src->water && !sectorToReach->water)
  2367. {
  2368. //TODO
  2369. //disembark
  2370. }
  2371. else
  2372. {
  2373. //TODO
  2374. //transition between two land/water sectors. Monolith? Whirlpool? ...
  2375. throw cannotFulfillGoalException("Land-land and water-water inter-sector transitions are not implemented!");
  2376. }
  2377. }
  2378. else
  2379. {
  2380. throw cannotFulfillGoalException("Inter-sector route detection failed: not connected sectors?");
  2381. }
  2382. }
  2383. else
  2384. {
  2385. makeParentBFS(h->visitablePos());
  2386. int3 curtile = dst;
  2387. while(curtile != h->visitablePos())
  2388. {
  2389. if(cb->getPathInfo(curtile)->reachable())
  2390. {
  2391. return curtile;
  2392. }
  2393. else
  2394. {
  2395. auto i = parent.find(curtile);
  2396. if(i != parent.end())
  2397. {
  2398. assert(curtile != i->second);
  2399. curtile = i->second;
  2400. }
  2401. else
  2402. throw cannotFulfillGoalException("Unreachable tile in sector? Should not happen!");
  2403. }
  2404. }
  2405. }
  2406. throw cannotFulfillGoalException("Impossible happened.");
  2407. }
  2408. void SectorMap::makeParentBFS(crint3 source)
  2409. {
  2410. parent.clear();
  2411. int mySector = retreiveTile(source);
  2412. std::queue<int3> toVisit;
  2413. toVisit.push(source);
  2414. while(!toVisit.empty())
  2415. {
  2416. int3 curPos = toVisit.front();
  2417. toVisit.pop();
  2418. ui8 &sec = retreiveTile(curPos);
  2419. assert(sec == mySector); //consider only tiles from the same sector
  2420. UNUSED(sec);
  2421. //const TerrainTile *t = cb->getTile(curPos);
  2422. foreach_neighbour(curPos, [&](crint3 neighPos)
  2423. {
  2424. if(retreiveTile(neighPos) == mySector && !vstd::contains(parent, neighPos))
  2425. {
  2426. toVisit.push(neighPos);
  2427. parent[neighPos] = curPos;
  2428. }
  2429. });
  2430. }
  2431. }
  2432. unsigned char & SectorMap::retreiveTile(crint3 pos)
  2433. {
  2434. return retreiveTileN(sector, pos);
  2435. }
  2436. const CGObjectInstance * ObjectIdRef::operator->() const
  2437. {
  2438. return cb->getObj(id, false);
  2439. }
  2440. ObjectIdRef::operator const CGObjectInstance*() const
  2441. {
  2442. return cb->getObj(id, false);
  2443. }
  2444. ObjectIdRef::ObjectIdRef(ObjectInstanceID _id) : id(_id)
  2445. {
  2446. }
  2447. ObjectIdRef::ObjectIdRef(const CGObjectInstance *obj) : id(obj->id)
  2448. {
  2449. }
  2450. bool ObjectIdRef::operator<(const ObjectIdRef &rhs) const
  2451. {
  2452. return id < rhs.id;
  2453. }
  2454. HeroPtr::HeroPtr(const CGHeroInstance *H)
  2455. {
  2456. if(!H)
  2457. {
  2458. //init from nullptr should equal to default init
  2459. *this = HeroPtr();
  2460. return;
  2461. }
  2462. h = H;
  2463. name = h->name;
  2464. hid = H->id;
  2465. // infosCount[ai->playerID][hid]++;
  2466. }
  2467. HeroPtr::HeroPtr()
  2468. {
  2469. h = nullptr;
  2470. hid = ObjectInstanceID();
  2471. }
  2472. HeroPtr::~HeroPtr()
  2473. {
  2474. // if(hid >= 0)
  2475. // infosCount[ai->playerID][hid]--;
  2476. }
  2477. bool HeroPtr::operator<(const HeroPtr &rhs) const
  2478. {
  2479. return hid < rhs.hid;
  2480. }
  2481. const CGHeroInstance * HeroPtr::get(bool doWeExpectNull /*= false*/) const
  2482. {
  2483. //TODO? check if these all assertions every time we get info about hero affect efficiency
  2484. //
  2485. //behave terribly when attempting unauthorized access to hero that is not ours (or was lost)
  2486. assert(doWeExpectNull || h);
  2487. if(h)
  2488. {
  2489. auto obj = cb->getObj(hid);
  2490. const bool owned = obj && obj->tempOwner == ai->playerID;
  2491. if(doWeExpectNull && !owned)
  2492. {
  2493. return nullptr;
  2494. }
  2495. else
  2496. {
  2497. assert(obj);
  2498. assert(owned);
  2499. }
  2500. }
  2501. return h;
  2502. }
  2503. const CGHeroInstance * HeroPtr::operator->() const
  2504. {
  2505. return get();
  2506. }
  2507. bool HeroPtr::validAndSet() const
  2508. {
  2509. return get(true);
  2510. }
  2511. const CGHeroInstance * HeroPtr::operator*() const
  2512. {
  2513. return get();
  2514. }