AIGateway.cpp 52 KB

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