AIGateway.cpp 45 KB

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