AIGateway.cpp 50 KB

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