VCAI.cpp 84 KB

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