AIGateway.cpp 46 KB

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