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