AIGateway.cpp 47 KB

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