AIGateway.cpp 53 KB

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