AIGateway.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845
  1. /*
  2. * AIGateway.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "../../lib/AsyncRunner.h"
  12. #include "../../lib/UnlockGuard.h"
  13. #include "../../lib/StartInfo.h"
  14. #include "../../lib/battle/CPlayerBattleCallback.h"
  15. #include "../../lib/entities/artifact/ArtifactUtils.h"
  16. #include "../../lib/entities/artifact/CArtifact.h"
  17. #include "../../lib/entities/building/CBuilding.h"
  18. #include "../../lib/mapObjects/MapObjects.h"
  19. #include "../../lib/mapObjects/ObjectTemplate.h"
  20. #include "../../lib/mapObjects/CGHeroInstance.h"
  21. #include "../../lib/CConfigHandler.h"
  22. #include "../../lib/IGameSettings.h"
  23. #include "../../lib/gameState/CGameState.h"
  24. #include "../../lib/gameState/UpgradeInfo.h"
  25. #include "../../lib/serializer/CTypeList.h"
  26. #include "../../lib/networkPacks/PacksForClient.h"
  27. #include "../../lib/networkPacks/PacksForClientBattle.h"
  28. #include "../../lib/networkPacks/PacksForServer.h"
  29. #include "../../lib/networkPacks/StackLocation.h"
  30. #include "../../lib/battle/BattleStateInfoForRetreat.h"
  31. #include "../../lib/battle/BattleInfo.h"
  32. #include "../../lib/CPlayerState.h"
  33. #include "AIGateway.h"
  34. #include "Goals/Goals.h"
  35. namespace NKAI
  36. {
  37. //one thread may be turn of AI and another will be handling a side effect for AI2
  38. thread_local CCallback * cb = nullptr;
  39. thread_local AIGateway * ai = nullptr;
  40. //helper RAII to manage global ai/cb ptrs
  41. struct SetGlobalState
  42. {
  43. SetGlobalState(AIGateway * AI)
  44. {
  45. assert(!ai);
  46. assert(!cb);
  47. ai = AI;
  48. cb = AI->myCb.get();
  49. }
  50. ~SetGlobalState()
  51. {
  52. //TODO: how to handle rm? shouldn't be called after ai is destroyed, hopefully
  53. //TODO: to ensure that, make rm unique_ptr
  54. ai = nullptr;
  55. cb = nullptr;
  56. }
  57. };
  58. #define SET_GLOBAL_STATE(ai) SetGlobalState _hlpSetState(ai)
  59. #define NET_EVENT_HANDLER SET_GLOBAL_STATE(this)
  60. #define MAKING_TURN SET_GLOBAL_STATE(this)
  61. AIGateway::AIGateway()
  62. :status(this)
  63. {
  64. LOG_TRACE(logAi);
  65. destinationTeleport = ObjectInstanceID();
  66. destinationTeleportPos = int3(-1);
  67. nullkiller.reset(new Nullkiller());
  68. asyncTasks = std::make_unique<AsyncRunner>();
  69. }
  70. AIGateway::~AIGateway()
  71. {
  72. LOG_TRACE(logAi);
  73. finish();
  74. nullkiller.reset();
  75. }
  76. void AIGateway::availableCreaturesChanged(const CGDwelling * town)
  77. {
  78. LOG_TRACE(logAi);
  79. NET_EVENT_HANDLER;
  80. }
  81. void AIGateway::heroMoved(const TryMoveHero & details, bool verbose)
  82. {
  83. LOG_TRACE(logAi);
  84. NET_EVENT_HANDLER;
  85. auto hero = cb->getHero(details.id);
  86. if(!hero)
  87. validateObject(details.id); //enemy hero may have left visible area
  88. nullkiller->invalidatePathfinderData();
  89. const int3 from = hero ? hero->convertToVisitablePos(details.start) : (details.start - int3(0,1,0));
  90. const int3 to = hero ? hero->convertToVisitablePos(details.end) : (details.end - int3(0,1,0));
  91. const CGObjectInstance * o1 = vstd::frontOrNull(cb->getVisitableObjs(from, verbose));
  92. const CGObjectInstance * o2 = vstd::frontOrNull(cb->getVisitableObjs(to, verbose));
  93. if(details.result == TryMoveHero::TELEPORTATION)
  94. {
  95. auto t1 = dynamic_cast<const CGTeleport *>(o1);
  96. auto t2 = dynamic_cast<const CGTeleport *>(o2);
  97. if(t1 && t2)
  98. {
  99. if(cb->isTeleportChannelBidirectional(t1->channel))
  100. {
  101. if(o1->ID == Obj::SUBTERRANEAN_GATE && o1->ID == o2->ID) // We need to only add subterranean gates in knownSubterraneanGates. Used for features not yet ported to use teleport channels
  102. {
  103. nullkiller->memory->addSubterraneanGate(o1, o2);
  104. }
  105. }
  106. }
  107. }
  108. else if(details.result == TryMoveHero::EMBARK && hero)
  109. {
  110. //make sure AI not attempt to visit used boat
  111. validateObject(hero->getBoat());
  112. }
  113. else if(details.result == TryMoveHero::DISEMBARK && o1)
  114. {
  115. auto boat = dynamic_cast<const CGBoat *>(o1);
  116. if(boat)
  117. addVisitableObj(boat);
  118. }
  119. }
  120. void AIGateway::heroInGarrisonChange(const CGTownInstance * town)
  121. {
  122. LOG_TRACE(logAi);
  123. NET_EVENT_HANDLER;
  124. }
  125. void AIGateway::centerView(int3 pos, int focusTime)
  126. {
  127. LOG_TRACE_PARAMS(logAi, "focusTime '%i'", focusTime);
  128. NET_EVENT_HANDLER;
  129. }
  130. void AIGateway::artifactMoved(const ArtifactLocation & src, const ArtifactLocation & dst)
  131. {
  132. LOG_TRACE(logAi);
  133. NET_EVENT_HANDLER;
  134. }
  135. void AIGateway::artifactAssembled(const ArtifactLocation & al)
  136. {
  137. LOG_TRACE(logAi);
  138. NET_EVENT_HANDLER;
  139. }
  140. void AIGateway::showTavernWindow(const CGObjectInstance * object, const CGHeroInstance * visitor, QueryID queryID)
  141. {
  142. LOG_TRACE(logAi);
  143. NET_EVENT_HANDLER;
  144. status.addQuery(queryID, "TavernWindow");
  145. executeActionAsync("showTavernWindow", [this, queryID](){ answerQuery(queryID, 0); });
  146. }
  147. void AIGateway::showThievesGuildWindow(const CGObjectInstance * obj)
  148. {
  149. LOG_TRACE(logAi);
  150. NET_EVENT_HANDLER;
  151. }
  152. void AIGateway::playerBlocked(int reason, bool start)
  153. {
  154. LOG_TRACE_PARAMS(logAi, "reason '%i', start '%i'", reason % start);
  155. NET_EVENT_HANDLER;
  156. if(start && reason == PlayerBlocked::UPCOMING_BATTLE)
  157. status.setBattle(UPCOMING_BATTLE);
  158. if(reason == PlayerBlocked::ONGOING_MOVEMENT)
  159. status.setMove(start);
  160. }
  161. void AIGateway::showPuzzleMap()
  162. {
  163. LOG_TRACE(logAi);
  164. NET_EVENT_HANDLER;
  165. }
  166. void AIGateway::showShipyardDialog(const IShipyard * obj)
  167. {
  168. LOG_TRACE(logAi);
  169. NET_EVENT_HANDLER;
  170. }
  171. void AIGateway::gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult)
  172. {
  173. LOG_TRACE_PARAMS(logAi, "victoryLossCheckResult '%s'", victoryLossCheckResult.messageToSelf.toString());
  174. NET_EVENT_HANDLER;
  175. logAi->debug("Player %d (%s): I heard that player %d (%s) %s.", playerID, playerID.toString(), player, player.toString(), (victoryLossCheckResult.victory() ? "won" : "lost"));
  176. // some whitespace to flush stream
  177. logAi->debug(std::string(200, ' '));
  178. if(player == playerID)
  179. {
  180. if(victoryLossCheckResult.victory())
  181. {
  182. logAi->debug("AIGateway: Player %d (%s) won. I won! Incredible!", player, player.toString());
  183. logAi->debug("Turn nr %d", myCb->getDate());
  184. }
  185. else
  186. {
  187. logAi->debug("AIGateway: Player %d (%s) lost. It's me. What a disappointment! :(", player, player.toString());
  188. }
  189. nullkiller->makingTurnInterrupption.interruptThread();
  190. }
  191. }
  192. void AIGateway::artifactPut(const ArtifactLocation & al)
  193. {
  194. LOG_TRACE(logAi);
  195. NET_EVENT_HANDLER;
  196. }
  197. void AIGateway::artifactRemoved(const ArtifactLocation & al)
  198. {
  199. LOG_TRACE(logAi);
  200. NET_EVENT_HANDLER;
  201. }
  202. void AIGateway::artifactDisassembled(const ArtifactLocation & al)
  203. {
  204. LOG_TRACE(logAi);
  205. NET_EVENT_HANDLER;
  206. }
  207. void AIGateway::heroVisit(const CGHeroInstance * visitor, const CGObjectInstance * visitedObj, bool start)
  208. {
  209. LOG_TRACE_PARAMS(logAi, "start '%i'; obj '%s'", start % (visitedObj ? visitedObj->getObjectName() : std::string("n/a")));
  210. NET_EVENT_HANDLER;
  211. if(start && visitedObj) //we can end visit with null object, anyway
  212. {
  213. nullkiller->memory->markObjectVisited(visitedObj);
  214. nullkiller->objectClusterizer->invalidate(visitedObj->id);
  215. }
  216. status.heroVisit(visitedObj, start);
  217. }
  218. void AIGateway::availableArtifactsChanged(const CGBlackMarket * bm)
  219. {
  220. LOG_TRACE(logAi);
  221. NET_EVENT_HANDLER;
  222. }
  223. void AIGateway::heroVisitsTown(const CGHeroInstance * hero, const CGTownInstance * town)
  224. {
  225. LOG_TRACE(logAi);
  226. NET_EVENT_HANDLER;
  227. }
  228. void AIGateway::tileHidden(const std::unordered_set<int3> & pos)
  229. {
  230. LOG_TRACE(logAi);
  231. NET_EVENT_HANDLER;
  232. nullkiller->memory->removeInvisibleObjects(myCb.get());
  233. }
  234. void AIGateway::tileRevealed(const std::unordered_set<int3> & pos)
  235. {
  236. LOG_TRACE(logAi);
  237. NET_EVENT_HANDLER;
  238. for(int3 tile : pos)
  239. {
  240. for(const CGObjectInstance * obj : myCb->getVisitableObjs(tile))
  241. addVisitableObj(obj);
  242. }
  243. if (nullkiller->settings->isUpdateHitmapOnTileReveal() && !pos.empty())
  244. nullkiller->dangerHitMap->resetTileOwners();
  245. }
  246. void AIGateway::heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query)
  247. {
  248. LOG_TRACE(logAi);
  249. NET_EVENT_HANDLER;
  250. auto firstHero = cb->getHero(hero1);
  251. auto secondHero = cb->getHero(hero2);
  252. status.addQuery(query, boost::str(boost::format("Exchange between heroes %s (%d) and %s (%d)") % firstHero->getNameTranslated() % firstHero->tempOwner % secondHero->getNameTranslated() % secondHero->tempOwner));
  253. executeActionAsync("heroExchangeStarted", [this, firstHero, secondHero, query]()
  254. {
  255. auto transferFrom2to1 = [this](const CGHeroInstance * h1, const CGHeroInstance * h2) -> void
  256. {
  257. this->pickBestCreatures(h1, h2);
  258. this->pickBestArtifacts(h1, h2);
  259. };
  260. //Do not attempt army or artifacts exchange if we visited ally player
  261. //Visits can still be useful if hero have skills like Scholar
  262. if(firstHero->tempOwner != secondHero->tempOwner)
  263. {
  264. logAi->debug("Heroes owned by different players. Do not exchange army or artifacts.");
  265. }
  266. else
  267. {
  268. if(nullkiller->isActive(firstHero))
  269. transferFrom2to1(secondHero, firstHero);
  270. else
  271. transferFrom2to1(firstHero, secondHero);
  272. }
  273. answerQuery(query, 0);
  274. });
  275. }
  276. void AIGateway::heroPrimarySkillChanged(const CGHeroInstance * hero, PrimarySkill which, si64 val)
  277. {
  278. LOG_TRACE_PARAMS(logAi, "which '%i', val '%i'", which.getNum() % val);
  279. NET_EVENT_HANDLER;
  280. }
  281. void AIGateway::showRecruitmentDialog(const CGDwelling * dwelling, const CArmedInstance * dst, int level, QueryID queryID)
  282. {
  283. LOG_TRACE_PARAMS(logAi, "level '%i'", level);
  284. NET_EVENT_HANDLER;
  285. status.addQuery(queryID, "RecruitmentDialog");
  286. executeActionAsync("showRecruitmentDialog", [this, dwelling, dst, queryID](){
  287. recruitCreatures(dwelling, dst);
  288. answerQuery(queryID, 0);
  289. });
  290. }
  291. void AIGateway::heroMovePointsChanged(const CGHeroInstance * hero)
  292. {
  293. LOG_TRACE(logAi);
  294. NET_EVENT_HANDLER;
  295. }
  296. void AIGateway::garrisonsChanged(ObjectInstanceID id1, ObjectInstanceID id2)
  297. {
  298. LOG_TRACE(logAi);
  299. NET_EVENT_HANDLER;
  300. }
  301. void AIGateway::newObject(const CGObjectInstance * obj)
  302. {
  303. LOG_TRACE(logAi);
  304. NET_EVENT_HANDLER;
  305. nullkiller->invalidatePathfinderData();
  306. if(obj->isVisitable())
  307. addVisitableObj(obj);
  308. }
  309. //to prevent AI from accessing objects that got deleted while they became invisible (Cover of Darkness, enemy hero moved etc.) below code allows AI to know deletion of objects out of sight
  310. //see: RemoveObject::applyFirstCl, to keep AI "not cheating" do not use advantage of this and use this function just to prevent crashes
  311. void AIGateway::objectRemoved(const CGObjectInstance * obj, const PlayerColor & initiator)
  312. {
  313. LOG_TRACE(logAi);
  314. NET_EVENT_HANDLER;
  315. if(!nullkiller) // crash protection
  316. return;
  317. nullkiller->memory->removeFromMemory(obj);
  318. nullkiller->objectClusterizer->onObjectRemoved(obj->id);
  319. if(nullkiller->baseGraph && nullkiller->isObjectGraphAllowed())
  320. {
  321. nullkiller->baseGraph->removeObject(obj);
  322. }
  323. if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
  324. {
  325. lostHero(cb->getHero(obj->id)); //we can promote, since objectRemoved is called just before actual deletion
  326. }
  327. if(obj->ID == Obj::HERO && cb->getPlayerRelations(obj->tempOwner, playerID) == PlayerRelations::ENEMIES)
  328. nullkiller->dangerHitMap->resetHitmap();
  329. if(obj->ID == Obj::TOWN)
  330. nullkiller->dangerHitMap->resetTileOwners();
  331. }
  332. void AIGateway::showHillFortWindow(const CGObjectInstance * object, const CGHeroInstance * visitor)
  333. {
  334. LOG_TRACE(logAi);
  335. NET_EVENT_HANDLER;
  336. }
  337. void AIGateway::playerBonusChanged(const Bonus & bonus, bool gain)
  338. {
  339. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  340. NET_EVENT_HANDLER;
  341. }
  342. void AIGateway::heroCreated(const CGHeroInstance * h)
  343. {
  344. LOG_TRACE(logAi);
  345. NET_EVENT_HANDLER;
  346. nullkiller->invalidatePathfinderData(); // new hero needs to look around
  347. }
  348. void AIGateway::advmapSpellCast(const CGHeroInstance * caster, SpellID spellID)
  349. {
  350. LOG_TRACE_PARAMS(logAi, "spellID '%i", spellID);
  351. NET_EVENT_HANDLER;
  352. }
  353. void AIGateway::showInfoDialog(EInfoWindowMode type, const std::string & text, const std::vector<Component> & components, int soundID)
  354. {
  355. LOG_TRACE_PARAMS(logAi, "soundID '%i'", soundID);
  356. NET_EVENT_HANDLER;
  357. }
  358. void AIGateway::requestRealized(PackageApplied * pa)
  359. {
  360. LOG_TRACE(logAi);
  361. NET_EVENT_HANDLER;
  362. if(status.haveTurn())
  363. {
  364. if(pa->packType == CTypeList::getInstance().getTypeID<EndTurn>(nullptr))
  365. {
  366. if(pa->result)
  367. status.madeTurn();
  368. }
  369. }
  370. if(pa->packType == CTypeList::getInstance().getTypeID<QueryReply>(nullptr))
  371. {
  372. status.receivedAnswerConfirmation(pa->requestID, pa->result);
  373. }
  374. }
  375. void AIGateway::receivedResource()
  376. {
  377. LOG_TRACE(logAi);
  378. NET_EVENT_HANDLER;
  379. }
  380. void AIGateway::showUniversityWindow(const IMarket * market, const CGHeroInstance * visitor, QueryID queryID)
  381. {
  382. LOG_TRACE(logAi);
  383. NET_EVENT_HANDLER;
  384. status.addQuery(queryID, "UniversityWindow");
  385. executeActionAsync("showUniversityWindow", [this, queryID](){ answerQuery(queryID, 0); });
  386. }
  387. void AIGateway::heroManaPointsChanged(const CGHeroInstance * hero)
  388. {
  389. LOG_TRACE(logAi);
  390. NET_EVENT_HANDLER;
  391. }
  392. void AIGateway::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  393. {
  394. LOG_TRACE_PARAMS(logAi, "which '%d', val '%d'", which % val);
  395. NET_EVENT_HANDLER;
  396. }
  397. void AIGateway::battleResultsApplied()
  398. {
  399. LOG_TRACE(logAi);
  400. NET_EVENT_HANDLER;
  401. assert(status.getBattle() == ENDING_BATTLE);
  402. status.setBattle(NO_BATTLE);
  403. }
  404. void AIGateway::beforeObjectPropertyChanged(const SetObjectProperty * sop)
  405. {
  406. }
  407. void AIGateway::objectPropertyChanged(const SetObjectProperty * sop)
  408. {
  409. LOG_TRACE(logAi);
  410. NET_EVENT_HANDLER;
  411. if(sop->what == ObjProperty::OWNER)
  412. {
  413. auto relations = myCb->getPlayerRelations(playerID, sop->identifier.as<PlayerColor>());
  414. auto obj = myCb->getObj(sop->id, false);
  415. if(!nullkiller) // crash protection
  416. return;
  417. if(obj)
  418. {
  419. if(relations == PlayerRelations::ENEMIES)
  420. {
  421. //we want to visit objects owned by oppponents
  422. //addVisitableObj(obj); // TODO: Remove once save compatibility broken. In past owned objects were removed from this set
  423. nullkiller->memory->markObjectUnvisited(obj);
  424. }
  425. else if(relations == PlayerRelations::SAME_PLAYER && obj->ID == Obj::TOWN)
  426. {
  427. // reevaluate defence for a new town
  428. nullkiller->dangerHitMap->resetHitmap();
  429. }
  430. }
  431. }
  432. }
  433. void AIGateway::buildChanged(const CGTownInstance * town, BuildingID buildingID, int what)
  434. {
  435. LOG_TRACE_PARAMS(logAi, "what '%i'", what);
  436. NET_EVENT_HANDLER;
  437. }
  438. void AIGateway::heroBonusChanged(const CGHeroInstance * hero, const Bonus & bonus, bool gain)
  439. {
  440. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  441. NET_EVENT_HANDLER;
  442. }
  443. void AIGateway::showMarketWindow(const IMarket * market, const CGHeroInstance * visitor, QueryID queryID)
  444. {
  445. LOG_TRACE(logAi);
  446. NET_EVENT_HANDLER;
  447. status.addQuery(queryID, "MarketWindow");
  448. executeActionAsync("showMarketWindow", [this, queryID](){ answerQuery(queryID, 0); });
  449. }
  450. void AIGateway::showWorldViewEx(const std::vector<ObjectPosInfo> & objectPositions, bool showTerrain)
  451. {
  452. //TODO: AI support for ViewXXX spell
  453. LOG_TRACE(logAi);
  454. NET_EVENT_HANDLER;
  455. }
  456. std::optional<BattleAction> AIGateway::makeSurrenderRetreatDecision(const BattleID & battleID, const BattleStateInfoForRetreat & battleState)
  457. {
  458. LOG_TRACE(logAi);
  459. NET_EVENT_HANDLER;
  460. if(battleState.ourHero && battleState.ourHero->patrol.patrolling)
  461. {
  462. return std::nullopt;
  463. }
  464. double ourStrength = battleState.getOurStrength();
  465. double fightRatio = ourStrength / (double)battleState.getEnemyStrength();
  466. // if we have no towns - things are already bad, so retreat is not an option.
  467. if(cb->getTownsInfo().size() && ourStrength < nullkiller->settings->getRetreatThresholdAbsolute() && fightRatio < nullkiller->settings->getRetreatThresholdRelative() && battleState.canFlee)
  468. {
  469. return BattleAction::makeRetreat(battleState.ourSide);
  470. }
  471. return std::nullopt;
  472. }
  473. void AIGateway::initGameInterface(std::shared_ptr<Environment> env, std::shared_ptr<CCallback> CB)
  474. {
  475. LOG_TRACE(logAi);
  476. myCb = CB;
  477. cbc = CB;
  478. this->env = env;
  479. NET_EVENT_HANDLER;
  480. playerID = *myCb->getPlayerID();
  481. myCb->waitTillRealize = true;
  482. nullkiller->init(CB, this);
  483. retrieveVisitableObjs();
  484. }
  485. void AIGateway::yourTurn(QueryID queryID)
  486. {
  487. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  488. NET_EVENT_HANDLER;
  489. nullkiller->invalidatePathfinderData();
  490. status.addQuery(queryID, "YourTurn");
  491. executeActionAsync("yourTurn", [this, queryID](){ answerQuery(queryID, 0); });
  492. status.startedTurn();
  493. nullkiller->makingTurnInterrupption.reset();
  494. asyncTasks->run([this]()
  495. {
  496. ScopedThreadName guard("NKAI::makingTurn");
  497. makeTurn();
  498. });
  499. }
  500. void AIGateway::heroGotLevel(const CGHeroInstance * hero, PrimarySkill pskill, std::vector<SecondarySkill> & skills, QueryID queryID)
  501. {
  502. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  503. NET_EVENT_HANDLER;
  504. status.addQuery(queryID, boost::str(boost::format("Hero %s got level %d") % hero->getNameTranslated() % hero->level));
  505. HeroPtr hPtr = hero;
  506. executeActionAsync("heroGotLevel", [this, hPtr, skills, queryID]()
  507. {
  508. int sel = 0;
  509. if(hPtr.validAndSet())
  510. {
  511. std::unique_lock lockGuard(nullkiller->aiStateMutex);
  512. nullkiller->heroManager->update();
  513. sel = nullkiller->heroManager->selectBestSkill(hPtr, skills);
  514. }
  515. answerQuery(queryID, sel);
  516. });
  517. }
  518. void AIGateway::commanderGotLevel(const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID)
  519. {
  520. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  521. NET_EVENT_HANDLER;
  522. status.addQuery(queryID, boost::str(boost::format("Commander %s of %s got level %d") % commander->name % commander->getArmy()->nodeName() % (int)commander->level));
  523. executeActionAsync("commanderGotLevel", [this, queryID](){ answerQuery(queryID, 0); });
  524. }
  525. void AIGateway::showBlockingDialog(const std::string & text, const std::vector<Component> & components, QueryID askID, const int soundID, bool selection, bool cancel, bool safeToAutoaccept)
  526. {
  527. LOG_TRACE_PARAMS(logAi, "text '%s', askID '%i', soundID '%i', selection '%i', cancel '%i', autoaccept '%i'", text % askID % soundID % selection % cancel % safeToAutoaccept);
  528. NET_EVENT_HANDLER;
  529. status.addQuery(askID, boost::str(boost::format("Blocking dialog query with %d components - %s")
  530. % components.size() % text));
  531. auto hero = nullkiller->getActiveHero();
  532. auto target = nullkiller->getTargetTile();
  533. if(!selection && cancel)
  534. {
  535. executeActionAsync("showBlockingDialog", [this, hero, target, askID]()
  536. {
  537. //yes&no -> always answer yes, we are a brave AI :)
  538. bool answer = true;
  539. auto objects = cb->getVisitableObjs(target);
  540. if(hero.validAndSet() && target.isValid() && objects.size())
  541. {
  542. auto topObj = objects.front()->id == hero->id ? objects.back() : objects.front();
  543. auto objType = topObj->ID; // top object should be our hero
  544. auto goalObjectID = nullkiller->getTargetObject();
  545. auto danger = nullkiller->dangerEvaluator->evaluateDanger(target, hero.get());
  546. auto ratio = static_cast<float>(danger) / hero->getTotalStrength();
  547. answer = true;
  548. if(topObj->id != goalObjectID && nullkiller->dangerEvaluator->evaluateDanger(topObj) > 0)
  549. {
  550. // no if we do not aim to visit this object
  551. answer = false;
  552. }
  553. logAi->trace("Query hook: %s(%s) by %s danger ratio %f", target.toString(), topObj->getObjectName(), hero.name(), ratio);
  554. if(cb->getObj(goalObjectID, false))
  555. {
  556. logAi->trace("AI expected %s", cb->getObj(goalObjectID, false)->getObjectName());
  557. }
  558. if(objType == Obj::BORDERGUARD || objType == Obj::QUEST_GUARD)
  559. {
  560. answer = true;
  561. }
  562. else if(objType == Obj::ARTIFACT || objType == Obj::RESOURCE)
  563. {
  564. bool dangerUnknown = danger == 0;
  565. bool dangerTooHigh = ratio * nullkiller->settings->getSafeAttackRatio() > 1;
  566. answer = !dangerUnknown && !dangerTooHigh;
  567. }
  568. }
  569. answerQuery(askID, answer ? 1 : 0);
  570. });
  571. return;
  572. }
  573. executeActionAsync("showBlockingDialog", [this, selection, components, hero, askID]()
  574. {
  575. int sel = 0;
  576. if(selection) //select from multiple components -> take the last one (they're indexed [1-size])
  577. sel = components.size();
  578. {
  579. std::unique_lock mxLock(nullkiller->aiStateMutex);
  580. // TODO: Find better way to understand it is Chest of Treasures
  581. if(hero.validAndSet()
  582. && components.size() == 2
  583. && components.front().type == ComponentType::RESOURCE
  584. && (nullkiller->heroManager->getHeroRole(hero) != HeroRole::MAIN
  585. || nullkiller->buildAnalyzer->isGoldPressureHigh()))
  586. {
  587. sel = 1;
  588. }
  589. }
  590. answerQuery(askID, sel);
  591. });
  592. }
  593. void AIGateway::showTeleportDialog(const CGHeroInstance * hero, TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID)
  594. {
  595. NET_EVENT_HANDLER;
  596. status.addQuery(askID, boost::str(boost::format("Teleport dialog query with %d exits") % exits.size()));
  597. int chosenExit = -1;
  598. if(impassable)
  599. {
  600. nullkiller->memory->knownTeleportChannels[channel]->passability = TeleportChannel::IMPASSABLE;
  601. }
  602. else if(destinationTeleport != ObjectInstanceID() && destinationTeleportPos.isValid())
  603. {
  604. auto neededExit = std::make_pair(destinationTeleport, destinationTeleportPos);
  605. if(destinationTeleport != ObjectInstanceID() && vstd::contains(exits, neededExit))
  606. chosenExit = vstd::find_pos(exits, neededExit);
  607. }
  608. for(auto exit : exits)
  609. {
  610. if(status.channelProbing() && exit.first == destinationTeleport)
  611. {
  612. chosenExit = vstd::find_pos(exits, exit);
  613. break;
  614. }
  615. else
  616. {
  617. // TODO: Implement checking if visiting that teleport will uncovert any FoW
  618. // So far this is the best option to handle decision about probing
  619. auto obj = cb->getObj(exit.first, false);
  620. if(obj == nullptr && !vstd::contains(teleportChannelProbingList, exit.first))
  621. {
  622. if(exit.first != destinationTeleport)
  623. teleportChannelProbingList.push_back(exit.first);
  624. }
  625. }
  626. }
  627. executeActionAsync("showTeleportDialog", [this, askID, chosenExit]()
  628. {
  629. answerQuery(askID, chosenExit);
  630. });
  631. }
  632. void AIGateway::showGarrisonDialog(const CArmedInstance * up, const CGHeroInstance * down, bool removableUnits, QueryID queryID)
  633. {
  634. LOG_TRACE_PARAMS(logAi, "removableUnits '%i', queryID '%i'", removableUnits % queryID);
  635. NET_EVENT_HANDLER;
  636. std::string s1 = up->nodeName();
  637. std::string s2 = down->nodeName();
  638. status.addQuery(queryID, boost::str(boost::format("Garrison dialog with %s and %s") % s1 % s2));
  639. //you can't request action from action-response thread
  640. executeActionAsync("showGarrisonDialog", [this, up, down, removableUnits, queryID]()
  641. {
  642. if(removableUnits && up->tempOwner == down->tempOwner && nullkiller->settings->isGarrisonTroopsUsageAllowed() && !cb->getStartInfo()->isRestorationOfErathiaCampaign())
  643. {
  644. pickBestCreatures(down, up);
  645. }
  646. answerQuery(queryID, 0);
  647. });
  648. }
  649. void AIGateway::showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects)
  650. {
  651. NET_EVENT_HANDLER;
  652. status.addQuery(askID, "Map object select query");
  653. executeActionAsync("showMapObjectSelectDialog", [this, askID](){ answerQuery(askID, selectedObject.getNum()); });
  654. }
  655. bool AIGateway::makePossibleUpgrades(const CArmedInstance * obj)
  656. {
  657. if(!obj)
  658. return false;
  659. bool upgraded = false;
  660. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  661. {
  662. if(const CStackInstance * s = obj->getStackPtr(SlotID(i)))
  663. {
  664. UpgradeInfo upgradeInfo(s->getId());
  665. do
  666. {
  667. myCb->fillUpgradeInfo(obj, SlotID(i), upgradeInfo);
  668. if(upgradeInfo.hasUpgrades())
  669. {
  670. // creature at given slot might have alternative upgrades, pick best one
  671. CreatureID upgID = *vstd::maxElementByFun(upgradeInfo.getAvailableUpgrades(), [](const CreatureID & id)
  672. {
  673. return id.toCreature()->getAIValue();
  674. });
  675. int oldValue = s->getCreature()->getAIValue();
  676. int newValue = upgID.toCreature()->getAIValue();
  677. if(newValue > oldValue && nullkiller->getFreeResources().canAfford(upgradeInfo.getUpgradeCostsFor(upgID) * s->getCount()))
  678. {
  679. myCb->upgradeCreature(obj, SlotID(i), upgID);
  680. upgraded = true;
  681. logAi->debug("Upgraded %d %s to %s", s->getCount(), upgradeInfo.oldID.toCreature()->getNamePluralTranslated(),
  682. upgradeInfo.getUpgrade().toCreature()->getNamePluralTranslated());
  683. }
  684. else
  685. break;
  686. }
  687. }
  688. while(upgradeInfo.hasUpgrades());
  689. }
  690. }
  691. return upgraded;
  692. }
  693. void AIGateway::makeTurn()
  694. {
  695. setThreadName("AIGateway::makeTurn");
  696. MAKING_TURN;
  697. auto day = cb->getDate(Date::DAY);
  698. logAi->info("Player %d (%s) starting turn, day %d", playerID, playerID.toString(), day);
  699. std::shared_lock gsLock(CGameState::mutex);
  700. if(nullkiller->isOpenMap())
  701. {
  702. cb->sendMessage("vcmieagles");
  703. }
  704. retrieveVisitableObjs();
  705. if(cb->getDate(Date::DAY_OF_WEEK) == 1)
  706. {
  707. for(const CGObjectInstance * obj : nullkiller->memory->visitableObjs)
  708. {
  709. if(isWeeklyRevisitable(nullkiller.get(), obj))
  710. {
  711. nullkiller->memory->markObjectUnvisited(obj);
  712. }
  713. }
  714. }
  715. #if NKAI_TRACE_LEVEL == 0
  716. try
  717. {
  718. #endif
  719. nullkiller->makeTurn();
  720. //for debug purpose
  721. for (auto h : cb->getHeroesInfo())
  722. {
  723. if (h->movementPointsRemaining())
  724. logAi->info("Hero %s has %d MP left", h->getNameTranslated(), h->movementPointsRemaining());
  725. }
  726. #if NKAI_TRACE_LEVEL == 0
  727. }
  728. catch (const TerminationRequestedException &)
  729. {
  730. logAi->debug("Making turn thread has been interrupted. We'll end without calling endTurn.");
  731. return;
  732. }
  733. catch (const std::exception & e)
  734. {
  735. logAi->debug("Making turn thread has caught an exception: %s", e.what());
  736. }
  737. #endif
  738. try
  739. {
  740. endTurn();
  741. }
  742. catch (const TerminationRequestedException &)
  743. {
  744. logAi->debug("Making turn thread has been interrupted. We'll end without calling endTurn.");
  745. return;
  746. }
  747. }
  748. void AIGateway::performObjectInteraction(const CGObjectInstance * obj, HeroPtr h)
  749. {
  750. LOG_TRACE_PARAMS(logAi, "Hero %s and object %s at %s", h->getNameTranslated() % obj->getObjectName() % obj->anchorPos().toString());
  751. switch(obj->ID)
  752. {
  753. case Obj::TOWN:
  754. if(h->getVisitedTown()) //we are inside, not just attacking
  755. {
  756. makePossibleUpgrades(h.get());
  757. std::unique_lock lockGuard(nullkiller->aiStateMutex);
  758. if(!h->getVisitedTown()->getGarrisonHero() || !nullkiller->isHeroLocked(h->getVisitedTown()->getGarrisonHero()))
  759. moveCreaturesToHero(h->getVisitedTown());
  760. if(nullkiller->heroManager->getHeroRole(h) == HeroRole::MAIN && !h->hasSpellbook()
  761. && nullkiller->getFreeGold() >= GameConstants::SPELLBOOK_GOLD_COST)
  762. {
  763. if(h->getVisitedTown()->hasBuilt(BuildingID::MAGES_GUILD_1))
  764. cb->buyArtifact(h.get(), ArtifactID::SPELLBOOK);
  765. }
  766. }
  767. break;
  768. case Obj::HILL_FORT:
  769. makePossibleUpgrades(h.get());
  770. break;
  771. }
  772. }
  773. void AIGateway::moveCreaturesToHero(const CGTownInstance * t)
  774. {
  775. if(t->getVisitingHero() && t->armedGarrison() && t->getVisitingHero()->tempOwner == t->tempOwner)
  776. {
  777. pickBestCreatures(t->getVisitingHero(), t->getUpperArmy());
  778. }
  779. }
  780. void AIGateway::pickBestCreatures(const CArmedInstance * destinationArmy, const CArmedInstance * source)
  781. {
  782. if(source->stacksCount() == 0)
  783. return;
  784. const CArmedInstance * armies[] = {destinationArmy, source};
  785. auto bestArmy = nullkiller->armyManager->getBestArmy(destinationArmy, destinationArmy, source, myCb->getTile(source->visitablePos())->getTerrainID());
  786. for(auto army : armies)
  787. {
  788. // move first stack at first slot if empty to avoid can not take away last creature
  789. if(!army->hasStackAtSlot(SlotID(0)) && army->stacksCount() > 0)
  790. {
  791. cb->mergeOrSwapStacks(
  792. army,
  793. army,
  794. SlotID(0),
  795. army->Slots().begin()->first);
  796. }
  797. }
  798. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  799. for(SlotID i = SlotID(0); i.validSlot(); i.advance(1)) //i-th strongest creature type will go to i-th slot
  800. {
  801. if(i.getNum() >= bestArmy.size())
  802. {
  803. if(destinationArmy->hasStackAtSlot(i))
  804. {
  805. auto creature = destinationArmy->getCreature(i);
  806. auto targetSlot = source->getSlotFor(creature);
  807. if(targetSlot.validSlot())
  808. {
  809. // remove unwanted creatures
  810. cb->mergeOrSwapStacks(destinationArmy, source, i, targetSlot);
  811. }
  812. else if(destinationArmy->getStack(i).getPower() < destinationArmy->getArmyStrength() / 100)
  813. {
  814. // dismiss creatures if the amount is small
  815. cb->dismissCreature(destinationArmy, i);
  816. }
  817. }
  818. continue;
  819. }
  820. const CCreature * targetCreature = bestArmy[i.getNum()].creature;
  821. for(auto armyPtr : armies)
  822. {
  823. for(SlotID j = SlotID(0); j.validSlot(); j.advance(1))
  824. {
  825. if(armyPtr->getCreature(j) == targetCreature && (i != j || armyPtr != destinationArmy)) //it's a searched creature not in dst SLOT
  826. {
  827. //can't take away last creature without split. generate a new stack with 1 creature which is weak but fast
  828. if(armyPtr == source
  829. && source->needsLastStack()
  830. && source->stacksCount() == 1
  831. && (!destinationArmy->hasStackAtSlot(i) || destinationArmy->getCreature(i) == targetCreature))
  832. {
  833. auto weakest = nullkiller->armyManager->getBestUnitForScout(bestArmy, myCb->getTile(source->visitablePos())->getTerrainID());
  834. if(weakest->creature == targetCreature)
  835. {
  836. if(1 == source->getStackCount(j))
  837. break;
  838. // move all except 1 of weakest creature from source to destination
  839. cb->splitStack(
  840. source,
  841. destinationArmy,
  842. j,
  843. destinationArmy->getSlotFor(targetCreature),
  844. destinationArmy->getStackCount(i) + source->getStackCount(j) - 1);
  845. break;
  846. }
  847. else
  848. {
  849. // Source last stack is not weakest. Move 1 of weakest creature from destination to source
  850. cb->splitStack(
  851. destinationArmy,
  852. source,
  853. destinationArmy->getSlotFor(weakest->creature),
  854. source->getFreeSlot(),
  855. 1);
  856. }
  857. }
  858. cb->mergeOrSwapStacks(armyPtr, destinationArmy, j, i);
  859. }
  860. }
  861. }
  862. }
  863. //TODO - having now strongest possible army, we may want to think about arranging stacks
  864. }
  865. void AIGateway::pickBestArtifacts(const CGHeroInstance * h, const CGHeroInstance * other)
  866. {
  867. auto equipBest = [](const CGHeroInstance * h, const CGHeroInstance * otherh, bool giveStuffToFirstHero) -> void
  868. {
  869. bool changeMade = false;
  870. std::set<std::pair<ArtifactInstanceID, ArtifactInstanceID> > swappedSet;
  871. do
  872. {
  873. changeMade = false;
  874. //we collect gear always in same order
  875. std::vector<ArtifactLocation> allArtifacts;
  876. if(giveStuffToFirstHero)
  877. {
  878. for(auto p : h->artifactsWorn)
  879. {
  880. if(p.second.getArt())
  881. allArtifacts.push_back(ArtifactLocation(h->id, p.first));
  882. }
  883. }
  884. for(auto slot : h->artifactsInBackpack)
  885. allArtifacts.push_back(ArtifactLocation(h->id, h->getArtPos(slot.getArt())));
  886. if(otherh)
  887. {
  888. for(auto p : otherh->artifactsWorn)
  889. {
  890. if(p.second.getArt())
  891. allArtifacts.push_back(ArtifactLocation(otherh->id, p.first));
  892. }
  893. for(auto slot : otherh->artifactsInBackpack)
  894. allArtifacts.push_back(ArtifactLocation(otherh->id, otherh->getArtPos(slot.getArt())));
  895. }
  896. //we give stuff to one hero or another, depending on giveStuffToFirstHero
  897. const CGHeroInstance * target = nullptr;
  898. if(giveStuffToFirstHero || !otherh)
  899. target = h;
  900. else
  901. target = otherh;
  902. for(auto location : allArtifacts)
  903. {
  904. if(location.artHolder == target->id && ArtifactUtils::isSlotEquipment(location.slot))
  905. continue; //don't reequip artifact we already wear
  906. if(location.slot == ArtifactPosition::MACH4) // don't attempt to move catapult
  907. continue;
  908. auto artHolder = cb->getHero(location.artHolder);
  909. auto s = artHolder->getSlot(location.slot);
  910. if(!s || s->locked) //we can't move locks
  911. continue;
  912. auto artifact = s->getArt();
  913. if(!artifact)
  914. continue;
  915. //FIXME: why are the above possible to be null?
  916. bool emptySlotFound = false;
  917. for(auto slot : artifact->getType()->getPossibleSlots().at(target->bearerType()))
  918. {
  919. if(target->isPositionFree(slot) && artifact->canBePutAt(target, slot, true)) //combined artifacts are not always allowed to move
  920. {
  921. ArtifactLocation destLocation(target->id, slot);
  922. cb->swapArtifacts(location, destLocation); //just put into empty slot
  923. emptySlotFound = true;
  924. changeMade = true;
  925. break;
  926. }
  927. }
  928. if(!emptySlotFound) //try to put that atifact in already occupied slot
  929. {
  930. int64_t artifactScore = getArtifactScoreForHero(target, artifact);
  931. for(auto slot : artifact->getType()->getPossibleSlots().at(target->bearerType()))
  932. {
  933. auto otherSlot = target->getSlot(slot);
  934. if(otherSlot && otherSlot->getArt()) //we need to exchange artifact for better one
  935. {
  936. int64_t otherArtifactScore = getArtifactScoreForHero(target, otherSlot->getArt());
  937. logAi->trace( "Comparing artifacts of %s: %s vs %s. Score: %d vs %d", target->getHeroTypeName(), artifact->getType()->getJsonKey(), otherSlot->getArt()->getType()->getJsonKey(), artifactScore, otherArtifactScore);
  938. //if that artifact is better than what we have, pick it
  939. //combined artifacts are not always allowed to move
  940. if(artifactScore > otherArtifactScore && artifact->canBePutAt(target, slot, true))
  941. {
  942. std::pair swapPair = std::minmax<ArtifactInstanceID>({artifact->getId(), otherSlot->artifactID});
  943. if (swappedSet.find(swapPair) != swappedSet.end())
  944. {
  945. logAi->warn(
  946. "Artifacts % s < -> % s have already swapped before, ignored.",
  947. artifact->getType()->getJsonKey(),
  948. otherSlot->getArt()->getType()->getJsonKey());
  949. continue;
  950. }
  951. logAi->trace(
  952. "Exchange artifacts %s <-> %s",
  953. artifact->getType()->getJsonKey(),
  954. otherSlot->getArt()->getType()->getJsonKey());
  955. if(!otherSlot->getArt()->canBePutAt(artHolder, location.slot, true))
  956. {
  957. ArtifactLocation destLocation(target->id, slot);
  958. ArtifactLocation backpack(artHolder->id, ArtifactPosition::BACKPACK_START);
  959. cb->swapArtifacts(destLocation, backpack);
  960. cb->swapArtifacts(location, destLocation);
  961. }
  962. else
  963. {
  964. cb->swapArtifacts(location, ArtifactLocation(target->id, target->getArtPos(otherSlot->getArt())));
  965. }
  966. changeMade = true;
  967. swappedSet.insert(swapPair);
  968. break;
  969. }
  970. }
  971. }
  972. }
  973. if(changeMade)
  974. break; //start evaluating artifacts from scratch
  975. }
  976. }
  977. while(changeMade);
  978. };
  979. equipBest(h, other, true);
  980. if(other)
  981. equipBest(h, other, false);
  982. }
  983. void AIGateway::recruitCreatures(const CGDwelling * d, const CArmedInstance * recruiter)
  984. {
  985. //now used only for visited dwellings / towns, not BuyArmy goal
  986. for(int i = 0; i < d->creatures.size(); i++)
  987. {
  988. if(!d->creatures[i].second.size())
  989. continue;
  990. int count = d->creatures[i].first;
  991. CreatureID creID = d->creatures[i].second.back();
  992. if(!recruiter->getSlotFor(creID).validSlot())
  993. {
  994. for(const auto & stack : recruiter->Slots())
  995. {
  996. if(!stack.second->getType())
  997. continue;
  998. auto duplicatingSlot = recruiter->getSlotFor(stack.second->getCreature());
  999. if(duplicatingSlot != stack.first)
  1000. {
  1001. cb->mergeStacks(recruiter, recruiter, stack.first, duplicatingSlot);
  1002. break;
  1003. }
  1004. }
  1005. if(!recruiter->getSlotFor(creID).validSlot())
  1006. {
  1007. continue;
  1008. }
  1009. }
  1010. vstd::amin(count, cb->getResourceAmount() / creID.toCreature()->getFullRecruitCost());
  1011. if(count > 0)
  1012. cb->recruitCreatures(d, recruiter, creID, count, i);
  1013. }
  1014. }
  1015. void AIGateway::battleStart(const BattleID & battleID, const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, BattleSide side, bool replayAllowed)
  1016. {
  1017. NET_EVENT_HANDLER;
  1018. assert(!playerID.isValidPlayer() || status.getBattle() == UPCOMING_BATTLE);
  1019. status.setBattle(ONGOING_BATTLE);
  1020. const CGObjectInstance * presumedEnemy = vstd::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
  1021. battlename = boost::str(boost::format("Starting battle of %s attacking %s at %s") % (hero1 ? hero1->getNameTranslated() : "a army") % (presumedEnemy ? presumedEnemy->getObjectName() : "unknown enemy") % tile.toString());
  1022. CAdventureAI::battleStart(battleID, army1, army2, tile, hero1, hero2, side, replayAllowed);
  1023. }
  1024. void AIGateway::battleEnd(const BattleID & battleID, const BattleResult * br, QueryID queryID)
  1025. {
  1026. NET_EVENT_HANDLER;
  1027. assert(status.getBattle() == ONGOING_BATTLE);
  1028. status.setBattle(ENDING_BATTLE);
  1029. bool won = br->winner == myCb->getBattle(battleID)->battleGetMySide();
  1030. logAi->debug("Player %d (%s): I %s the %s!", playerID, playerID.toString(), (won ? "won" : "lost"), battlename);
  1031. battlename.clear();
  1032. CAdventureAI::battleEnd(battleID, br, queryID);
  1033. // gosolo
  1034. if(queryID != QueryID::NONE && myCb->getPlayerState(playerID)->isHuman())
  1035. {
  1036. status.addQuery(queryID, "Confirm battle query");
  1037. executeActionAsync("battleEnd", [this, queryID]()
  1038. {
  1039. answerQuery(queryID, 0);
  1040. });
  1041. }
  1042. }
  1043. void AIGateway::waitTillFree()
  1044. {
  1045. auto unlock = vstd::makeUnlockSharedGuard(CGameState::mutex);
  1046. status.waitTillFree();
  1047. }
  1048. void AIGateway::retrieveVisitableObjs()
  1049. {
  1050. foreach_tile_pos([&](const int3 & pos)
  1051. {
  1052. for(const CGObjectInstance * obj : myCb->getVisitableObjs(pos, false))
  1053. {
  1054. addVisitableObj(obj);
  1055. }
  1056. });
  1057. }
  1058. std::vector<const CGObjectInstance *> AIGateway::getFlaggedObjects() const
  1059. {
  1060. std::vector<const CGObjectInstance *> ret;
  1061. for(const CGObjectInstance * obj : nullkiller->memory->visitableObjs)
  1062. {
  1063. if(obj->tempOwner == playerID)
  1064. ret.push_back(obj);
  1065. }
  1066. return ret;
  1067. }
  1068. void AIGateway::addVisitableObj(const CGObjectInstance * obj)
  1069. {
  1070. if(obj->ID == Obj::EVENT)
  1071. return;
  1072. nullkiller->memory->addVisitableObject(obj);
  1073. if(obj->ID == Obj::HERO && cb->getPlayerRelations(obj->tempOwner, playerID) == PlayerRelations::ENEMIES)
  1074. {
  1075. nullkiller->dangerHitMap->resetHitmap();
  1076. }
  1077. }
  1078. bool AIGateway::moveHeroToTile(int3 dst, HeroPtr h)
  1079. {
  1080. if(h->isGarrisoned() && h->getVisitedTown())
  1081. {
  1082. cb->swapGarrisonHero(h->getVisitedTown());
  1083. moveCreaturesToHero(h->getVisitedTown());
  1084. }
  1085. //TODO: consider if blockVisit objects change something in our checks: AIUtility::isBlockVisitObj()
  1086. auto afterMovementCheck = [&]() -> void
  1087. {
  1088. waitTillFree(); //movement may cause battle or blocking dialog
  1089. if(!h)
  1090. {
  1091. lostHero(h);
  1092. teleportChannelProbingList.clear();
  1093. if(status.channelProbing()) // if hero lost during channel probing we need to switch this mode off
  1094. status.setChannelProbing(false);
  1095. throw cannotFulfillGoalException("Hero was lost!");
  1096. }
  1097. };
  1098. logAi->debug("Moving hero %s to tile %s", h->getNameTranslated(), dst.toString());
  1099. int3 startHpos = h->visitablePos();
  1100. bool ret = false;
  1101. if(startHpos == dst)
  1102. {
  1103. //FIXME: this assertion fails also if AI moves onto defeated guarded object
  1104. //assert(cb->getVisitableObjs(dst).size() > 1); //there's no point in revisiting tile where there is no visitable object
  1105. cb->moveHero(*h, h->convertFromVisitablePos(dst), false);
  1106. afterMovementCheck(); // TODO: is it feasible to hero get killed there if game work properly?
  1107. // If revisiting, teleport probing is never done, and so the entries into the list would remain unused and uncleared
  1108. teleportChannelProbingList.clear();
  1109. // not sure if AI can currently reconsider to attack bank while staying on it. Check issue 2084 on mantis for more information.
  1110. ret = true;
  1111. }
  1112. else
  1113. {
  1114. CGPath path;
  1115. nullkiller->getPathsInfo(h.get())->getPath(path, dst);
  1116. if(path.nodes.empty())
  1117. {
  1118. logAi->error("Hero %s cannot reach %s.", h->getNameTranslated(), dst.toString());
  1119. return true;
  1120. }
  1121. int i = (int)path.nodes.size() - 1;
  1122. auto getObj = [&](int3 coord, bool ignoreHero)
  1123. {
  1124. auto tile = cb->getTile(coord, false);
  1125. assert(tile);
  1126. return cb->getObj(tile->topVisitableObj(ignoreHero), false);
  1127. };
  1128. auto isTeleportAction = [&](EPathNodeAction action) -> bool
  1129. {
  1130. if(action != EPathNodeAction::TELEPORT_NORMAL && action != EPathNodeAction::TELEPORT_BLOCKING_VISIT)
  1131. {
  1132. if(action != EPathNodeAction::TELEPORT_BATTLE)
  1133. {
  1134. return false;
  1135. }
  1136. }
  1137. return true;
  1138. };
  1139. auto getDestTeleportObj = [&](const CGObjectInstance * currentObject, const CGObjectInstance * nextObjectTop, const CGObjectInstance * nextObject) -> const CGObjectInstance *
  1140. {
  1141. if(CGTeleport::isConnected(currentObject, nextObjectTop))
  1142. return nextObjectTop;
  1143. if(nextObjectTop && nextObjectTop->ID == Obj::HERO)
  1144. {
  1145. if(CGTeleport::isConnected(currentObject, nextObject))
  1146. return nextObject;
  1147. }
  1148. return nullptr;
  1149. };
  1150. auto doMovement = [&](int3 dst, bool transit)
  1151. {
  1152. cb->moveHero(*h, h->convertFromVisitablePos(dst), transit);
  1153. };
  1154. auto doTeleportMovement = [&](ObjectInstanceID exitId, int3 exitPos)
  1155. {
  1156. if(cb->getObj(exitId) && cb->getObj(exitId)->ID == Obj::WHIRLPOOL)
  1157. {
  1158. nullkiller->armyFormation->rearrangeArmyForWhirlpool(*h);
  1159. }
  1160. destinationTeleport = exitId;
  1161. if(exitPos.isValid())
  1162. destinationTeleportPos = exitPos;
  1163. cb->moveHero(*h, h->pos, false);
  1164. destinationTeleport = ObjectInstanceID();
  1165. destinationTeleportPos = int3(-1);
  1166. afterMovementCheck();
  1167. };
  1168. auto doChannelProbing = [&]() -> void
  1169. {
  1170. auto currentPos = h->visitablePos();
  1171. auto currentTeleport = getObj(currentPos, true);
  1172. if(currentTeleport)
  1173. {
  1174. auto currentExit = currentTeleport->id;
  1175. status.setChannelProbing(true);
  1176. for(auto exit : teleportChannelProbingList)
  1177. doTeleportMovement(exit, int3(-1));
  1178. teleportChannelProbingList.clear();
  1179. status.setChannelProbing(false);
  1180. doTeleportMovement(currentExit, currentPos);
  1181. }
  1182. else
  1183. {
  1184. logAi->debug("Unexpected channel probbing at " + currentPos.toString());
  1185. teleportChannelProbingList.clear();
  1186. status.setChannelProbing(false);
  1187. }
  1188. };
  1189. teleportChannelProbingList.clear();
  1190. status.setChannelProbing(false);
  1191. for(; i > 0; i--)
  1192. {
  1193. int3 currentCoord = path.nodes[i].coord;
  1194. int3 nextCoord = path.nodes[i - 1].coord;
  1195. auto currentObject = getObj(currentCoord, currentCoord == h->visitablePos());
  1196. auto nextObjectTop = getObj(nextCoord, false);
  1197. auto nextObject = getObj(nextCoord, true);
  1198. auto destTeleportObj = getDestTeleportObj(currentObject, nextObjectTop, nextObject);
  1199. if(isTeleportAction(path.nodes[i - 1].action) && destTeleportObj != nullptr)
  1200. {
  1201. //we use special login if hero standing on teleporter it's mean we need
  1202. doTeleportMovement(destTeleportObj->id, nextCoord);
  1203. if(teleportChannelProbingList.size())
  1204. doChannelProbing();
  1205. nullkiller->memory->markObjectVisited(destTeleportObj); //FIXME: Monoliths are not correctly visited
  1206. continue;
  1207. }
  1208. //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  1209. if(path.nodes[i - 1].turns)
  1210. {
  1211. //blockedHeroes.insert(h); //to avoid attempts of moving heroes with very little MPs
  1212. return false;
  1213. }
  1214. int3 endpos = path.nodes[i - 1].coord;
  1215. if(endpos == h->visitablePos())
  1216. continue;
  1217. bool isConnected = false;
  1218. bool isNextObjectTeleport = false;
  1219. // Check there is node after next one; otherwise transit is pointless
  1220. if(i - 2 >= 0)
  1221. {
  1222. isConnected = CGTeleport::isConnected(nextObjectTop, getObj(path.nodes[i - 2].coord, false));
  1223. isNextObjectTeleport = CGTeleport::isTeleport(nextObjectTop);
  1224. }
  1225. if(isConnected || isNextObjectTeleport)
  1226. {
  1227. // Hero should be able to go through object if it's allow transit
  1228. doMovement(endpos, true);
  1229. }
  1230. else if(path.nodes[i - 1].layer == EPathfindingLayer::AIR)
  1231. {
  1232. doMovement(endpos, true);
  1233. }
  1234. else
  1235. {
  1236. doMovement(endpos, false);
  1237. }
  1238. afterMovementCheck();
  1239. if(teleportChannelProbingList.size())
  1240. doChannelProbing();
  1241. }
  1242. if(path.nodes[0].action == EPathNodeAction::BLOCKING_VISIT || path.nodes[0].action == EPathNodeAction::BATTLE)
  1243. {
  1244. // when we take resource we do not reach its position. We even might not move
  1245. // also guarded town is not get visited automatically after capturing
  1246. ret = h && i == 0;
  1247. }
  1248. }
  1249. if(h)
  1250. {
  1251. if(auto visitedObject = vstd::frontOrNull(cb->getVisitableObjs(h->visitablePos()))) //we stand on something interesting
  1252. {
  1253. if(visitedObject != *h)
  1254. {
  1255. performObjectInteraction(visitedObject, h);
  1256. ret = true;
  1257. }
  1258. }
  1259. }
  1260. if(h) //we could have lost hero after last move
  1261. {
  1262. ret = ret || (dst == h->visitablePos());
  1263. if(startHpos == h->visitablePos() && !ret) //we didn't move and didn't reach the target
  1264. {
  1265. throw cannotFulfillGoalException("Invalid path found!");
  1266. }
  1267. logAi->debug("Hero %s moved from %s to %s. Returning %d.", h->getNameTranslated(), startHpos.toString(), h->visitablePos().toString(), ret);
  1268. }
  1269. return ret;
  1270. }
  1271. void AIGateway::buildStructure(const CGTownInstance * t, BuildingID building)
  1272. {
  1273. auto name = t->getTown()->buildings.at(building)->getNameTranslated();
  1274. logAi->debug("Player %d will build %s in town of %s at %s", ai->playerID, name, t->getNameTranslated(), t->anchorPos().toString());
  1275. cb->buildBuilding(t, building); //just do this;
  1276. }
  1277. void AIGateway::tryRealize(Goals::DigAtTile & g)
  1278. {
  1279. assert(g.hero->visitablePos() == g.tile); //surely we want to crash here?
  1280. if(g.hero->diggingStatus() == EDiggingStatus::CAN_DIG)
  1281. {
  1282. cb->dig(g.hero);
  1283. }
  1284. else
  1285. {
  1286. throw cannotFulfillGoalException("A hero can't dig!\n");
  1287. }
  1288. }
  1289. void AIGateway::tryRealize(Goals::Trade & g) //trade
  1290. {
  1291. if(cb->getResourceAmount(GameResID(g.resID)) >= g.value) //goal is already fulfilled. Why we need this check, anyway?
  1292. throw goalFulfilledException(sptr(g));
  1293. int acquiredResources = 0;
  1294. if(const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(g.objid), false))
  1295. {
  1296. if(const auto * m = dynamic_cast<const IMarket*>(obj))
  1297. {
  1298. auto freeRes = cb->getResourceAmount(); //trade only resources which are not reserved
  1299. for(auto it = ResourceSet::nziterator(freeRes); it.valid(); it++)
  1300. {
  1301. auto res = it->resType;
  1302. if(res.getNum() == g.resID) //sell any other resource
  1303. continue;
  1304. int toGive;
  1305. int toGet;
  1306. m->getOffer(res.getNum(), g.resID, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  1307. toGive = static_cast<int>(toGive * (it->resVal / toGive)); //round down
  1308. //TODO trade only as much as needed
  1309. if (toGive) //don't try to sell 0 resources
  1310. {
  1311. cb->trade(m->getObjInstanceID(), EMarketMode::RESOURCE_RESOURCE, res, GameResID(g.resID), toGive);
  1312. acquiredResources = static_cast<int>(toGet * (it->resVal / toGive));
  1313. logAi->debug("Traded %d of %s for %d of %s at %s", toGive, res, acquiredResources, g.resID, obj->getObjectName());
  1314. }
  1315. if (cb->getResourceAmount(GameResID(g.resID)))
  1316. throw goalFulfilledException(sptr(g)); //we traded all we needed
  1317. }
  1318. throw cannotFulfillGoalException("I cannot get needed resources by trade!");
  1319. }
  1320. else
  1321. {
  1322. throw cannotFulfillGoalException("I don't know how to use this object to raise resources!");
  1323. }
  1324. }
  1325. else
  1326. {
  1327. throw cannotFulfillGoalException("No object that could be used to raise resources!");
  1328. }
  1329. }
  1330. void AIGateway::endTurn()
  1331. {
  1332. logAi->info("Player %d (%s) ends turn", playerID, playerID.toString());
  1333. if(!status.haveTurn())
  1334. {
  1335. logAi->error("Not having turn at the end of turn???");
  1336. }
  1337. logAi->debug("Resources at the end of turn: %s", cb->getResourceAmount().toString());
  1338. if(cb->getPlayerStatus(playerID) != EPlayerStatus::INGAME)
  1339. {
  1340. logAi->info("Ending turn is not needed because we already lost");
  1341. return;
  1342. }
  1343. do
  1344. {
  1345. cb->endTurn();
  1346. }
  1347. 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
  1348. logGlobal->info("Player %d (%s) ended turn", playerID, playerID.toString());
  1349. }
  1350. void AIGateway::buildArmyIn(const CGTownInstance * t)
  1351. {
  1352. makePossibleUpgrades(t->getVisitingHero());
  1353. makePossibleUpgrades(t);
  1354. recruitCreatures(t, t->getUpperArmy());
  1355. moveCreaturesToHero(t);
  1356. }
  1357. void AIGateway::finish()
  1358. {
  1359. nullkiller->makingTurnInterrupption.interruptThread();
  1360. if (asyncTasks)
  1361. {
  1362. asyncTasks->wait();
  1363. asyncTasks.reset();
  1364. }
  1365. }
  1366. void AIGateway::executeActionAsync(const std::string & description, const std::function<void()> & whatToDo)
  1367. {
  1368. if (!asyncTasks)
  1369. throw std::runtime_error("Attempt to execute task on shut down AI state!");
  1370. asyncTasks->run([this, description, whatToDo]()
  1371. {
  1372. ScopedThreadName guard("NKAI::" + description);
  1373. SET_GLOBAL_STATE(this);
  1374. std::shared_lock gsLock(CGameState::mutex);
  1375. whatToDo();
  1376. });
  1377. }
  1378. void AIGateway::lostHero(HeroPtr h)
  1379. {
  1380. logAi->debug("I lost my hero %s. It's best to forget and move on.", h.name());
  1381. nullkiller->invalidatePathfinderData();
  1382. }
  1383. void AIGateway::answerQuery(QueryID queryID, int selection)
  1384. {
  1385. logAi->debug("I'll answer the query %d giving the choice %d", queryID, selection);
  1386. if(queryID != QueryID(-1))
  1387. {
  1388. cb->selectionMade(selection, queryID);
  1389. }
  1390. else
  1391. {
  1392. logAi->debug("Since the query ID is %d, the answer won't be sent. This is not a real query!", queryID);
  1393. //do nothing
  1394. }
  1395. }
  1396. void AIGateway::requestSent(const CPackForServer * pack, int requestID)
  1397. {
  1398. //BNLOG("I have sent request of type %s", typeid(*pack).name());
  1399. if(auto reply = dynamic_cast<const QueryReply *>(pack))
  1400. {
  1401. status.attemptedAnsweringQuery(reply->qid, requestID);
  1402. }
  1403. }
  1404. std::string AIGateway::getBattleAIName() const
  1405. {
  1406. if(settings["server"]["enemyAI"].getType() == JsonNode::JsonType::DATA_STRING)
  1407. return settings["server"]["enemyAI"].String();
  1408. else
  1409. return "BattleAI";
  1410. }
  1411. void AIGateway::validateObject(const CGObjectInstance * obj)
  1412. {
  1413. validateObject(obj->id);
  1414. }
  1415. void AIGateway::validateObject(ObjectIdRef obj)
  1416. {
  1417. if(!obj)
  1418. {
  1419. nullkiller->memory->removeFromMemory(obj);
  1420. }
  1421. }
  1422. AIStatus::AIStatus(AIGateway * gateway)
  1423. : gateway(gateway)
  1424. {
  1425. battle = NO_BATTLE;
  1426. havingTurn = false;
  1427. ongoingHeroMovement = false;
  1428. ongoingChannelProbing = false;
  1429. }
  1430. AIStatus::~AIStatus()
  1431. {
  1432. }
  1433. void AIStatus::setBattle(BattleState BS)
  1434. {
  1435. std::unique_lock<std::mutex> lock(mx);
  1436. LOG_TRACE_PARAMS(logAi, "battle state=%d", (int)BS);
  1437. battle = BS;
  1438. cv.notify_all();
  1439. }
  1440. BattleState AIStatus::getBattle()
  1441. {
  1442. std::unique_lock<std::mutex> lock(mx);
  1443. return battle;
  1444. }
  1445. void AIStatus::addQuery(QueryID ID, std::string description)
  1446. {
  1447. if(ID == QueryID(-1))
  1448. {
  1449. logAi->debug("The \"query\" has an id %d, it'll be ignored as non-query. Description: %s", ID, description);
  1450. return;
  1451. }
  1452. assert(ID.getNum() >= 0);
  1453. std::unique_lock<std::mutex> lock(mx);
  1454. assert(!vstd::contains(remainingQueries, ID));
  1455. remainingQueries[ID] = description;
  1456. cv.notify_all();
  1457. logAi->debug("Adding query %d - %s. Total queries count: %d", ID, description, remainingQueries.size());
  1458. }
  1459. void AIStatus::removeQuery(QueryID ID)
  1460. {
  1461. std::unique_lock<std::mutex> lock(mx);
  1462. assert(vstd::contains(remainingQueries, ID));
  1463. std::string description = remainingQueries[ID];
  1464. remainingQueries.erase(ID);
  1465. cv.notify_all();
  1466. logAi->debug("Removing query %d - %s. Total queries count: %d", ID, description, remainingQueries.size());
  1467. }
  1468. int AIStatus::getQueriesCount()
  1469. {
  1470. std::unique_lock<std::mutex> lock(mx);
  1471. return static_cast<int>(remainingQueries.size());
  1472. }
  1473. void AIStatus::startedTurn()
  1474. {
  1475. std::unique_lock<std::mutex> lock(mx);
  1476. havingTurn = true;
  1477. cv.notify_all();
  1478. }
  1479. void AIStatus::madeTurn()
  1480. {
  1481. std::unique_lock<std::mutex> lock(mx);
  1482. havingTurn = false;
  1483. cv.notify_all();
  1484. }
  1485. void AIStatus::waitTillFree()
  1486. {
  1487. std::unique_lock<std::mutex> lock(mx);
  1488. while(battle != NO_BATTLE || !remainingQueries.empty() || !objectsBeingVisited.empty() || ongoingHeroMovement)
  1489. {
  1490. cv.wait_for(lock, std::chrono::milliseconds(10));
  1491. gateway->nullkiller->makingTurnInterrupption.interruptionPoint();
  1492. }
  1493. }
  1494. bool AIStatus::haveTurn()
  1495. {
  1496. std::unique_lock<std::mutex> lock(mx);
  1497. return havingTurn;
  1498. }
  1499. void AIStatus::attemptedAnsweringQuery(QueryID queryID, int answerRequestID)
  1500. {
  1501. std::unique_lock<std::mutex> lock(mx);
  1502. assert(vstd::contains(remainingQueries, queryID));
  1503. std::string description = remainingQueries[queryID];
  1504. logAi->debug("Attempted answering query %d - %s. Request id=%d. Waiting for results...", queryID, description, answerRequestID);
  1505. requestToQueryID[answerRequestID] = queryID;
  1506. }
  1507. void AIStatus::receivedAnswerConfirmation(int answerRequestID, int result)
  1508. {
  1509. assert(vstd::contains(requestToQueryID, answerRequestID));
  1510. QueryID query = requestToQueryID[answerRequestID];
  1511. assert(vstd::contains(remainingQueries, query));
  1512. requestToQueryID.erase(answerRequestID);
  1513. if(result)
  1514. {
  1515. removeQuery(query);
  1516. }
  1517. else
  1518. {
  1519. logAi->error("Something went really wrong, failed to answer query %d : %s", query.getNum(), remainingQueries[query]);
  1520. //TODO safely retry
  1521. }
  1522. }
  1523. void AIStatus::heroVisit(const CGObjectInstance * obj, bool started)
  1524. {
  1525. std::unique_lock<std::mutex> lock(mx);
  1526. if(started)
  1527. {
  1528. objectsBeingVisited.push_back(obj);
  1529. }
  1530. else
  1531. {
  1532. // There can be more than one object visited at the time (eg. hero visits Subterranean Gate
  1533. // causing visit to hero on the other side.
  1534. // However, we are guaranteed that start/end visit notification maintain stack order.
  1535. assert(!objectsBeingVisited.empty());
  1536. objectsBeingVisited.pop_back();
  1537. }
  1538. cv.notify_all();
  1539. }
  1540. void AIStatus::setMove(bool ongoing)
  1541. {
  1542. std::unique_lock<std::mutex> lock(mx);
  1543. ongoingHeroMovement = ongoing;
  1544. cv.notify_all();
  1545. }
  1546. void AIStatus::setChannelProbing(bool ongoing)
  1547. {
  1548. std::unique_lock<std::mutex> lock(mx);
  1549. ongoingChannelProbing = ongoing;
  1550. cv.notify_all();
  1551. }
  1552. bool AIStatus::channelProbing()
  1553. {
  1554. return ongoingChannelProbing;
  1555. }
  1556. void AIGateway::invalidatePaths()
  1557. {
  1558. nullkiller->invalidatePaths();
  1559. }
  1560. }