AIGateway.cpp 47 KB

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