AIGateway.cpp 47 KB

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