VCAI.cpp 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884
  1. /*
  2. * VCAI.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 "VCAI.h"
  12. #include "FuzzyHelper.h"
  13. #include "ResourceManager.h"
  14. #include "BuildingManager.h"
  15. #include "Goals/Goals.h"
  16. #include "../../lib/UnlockGuard.h"
  17. #include "../../lib/mapObjects/MapObjects.h"
  18. #include "../../lib/mapObjects/ObjectTemplate.h"
  19. #include "../../lib/CConfigHandler.h"
  20. #include "../../lib/CHeroHandler.h"
  21. #include "../../lib/GameSettings.h"
  22. #include "../../lib/CGameState.h"
  23. #include "../../lib/NetPacksBase.h"
  24. #include "../../lib/NetPacks.h"
  25. #include "../../lib/bonuses/CBonusSystemNode.h"
  26. #include "../../lib/bonuses/Limiters.h"
  27. #include "../../lib/bonuses/Updaters.h"
  28. #include "../../lib/bonuses/Propagators.h"
  29. #include "../../lib/serializer/CTypeList.h"
  30. #include "../../lib/serializer/BinarySerializer.h"
  31. #include "../../lib/serializer/BinaryDeserializer.h"
  32. #include "AIhelper.h"
  33. extern FuzzyHelper * fh;
  34. const double SAFE_ATTACK_CONSTANT = 1.5;
  35. //one thread may be turn of AI and another will be handling a side effect for AI2
  36. boost::thread_specific_ptr<CCallback> cb;
  37. boost::thread_specific_ptr<VCAI> ai;
  38. //std::map<int, std::map<int, int> > HeroView::infosCount;
  39. //helper RAII to manage global ai/cb ptrs
  40. struct SetGlobalState
  41. {
  42. SetGlobalState(VCAI * AI)
  43. {
  44. assert(!ai.get());
  45. assert(!cb.get());
  46. ai.reset(AI);
  47. cb.reset(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.release();
  54. cb.release();
  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. VCAI::VCAI()
  61. {
  62. LOG_TRACE(logAi);
  63. makingTurn = nullptr;
  64. destinationTeleport = ObjectInstanceID();
  65. destinationTeleportPos = int3(-1);
  66. ah = new AIhelper();
  67. ah->setAI(this);
  68. }
  69. VCAI::~VCAI()
  70. {
  71. delete ah;
  72. LOG_TRACE(logAi);
  73. finish();
  74. }
  75. void VCAI::availableCreaturesChanged(const CGDwelling * town)
  76. {
  77. LOG_TRACE(logAi);
  78. NET_EVENT_HANDLER;
  79. }
  80. void VCAI::heroMoved(const TryMoveHero & details, bool verbose)
  81. {
  82. LOG_TRACE(logAi);
  83. NET_EVENT_HANDLER;
  84. //enemy hero may have left visible area
  85. validateObject(details.id);
  86. auto hero = cb->getHero(details.id);
  87. const int3 from = hero ? hero->convertToVisitablePos(details.start) : (details.start - int3(0,1,0));;
  88. const int3 to = hero ? hero->convertToVisitablePos(details.end) : (details.end - int3(0,1,0));
  89. const CGObjectInstance * o1 = vstd::frontOrNull(cb->getVisitableObjs(from, verbose));
  90. const CGObjectInstance * o2 = vstd::frontOrNull(cb->getVisitableObjs(to, verbose));
  91. if(details.result == TryMoveHero::TELEPORTATION)
  92. {
  93. auto t1 = dynamic_cast<const CGTeleport *>(o1);
  94. auto t2 = dynamic_cast<const CGTeleport *>(o2);
  95. if(t1 && t2)
  96. {
  97. if(cb->isTeleportChannelBidirectional(t1->channel))
  98. {
  99. 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
  100. {
  101. knownSubterraneanGates[o1] = o2;
  102. knownSubterraneanGates[o2] = o1;
  103. logAi->debug("Found a pair of subterranean gates between %s and %s!", from.toString(), to.toString());
  104. }
  105. }
  106. }
  107. //FIXME: teleports are not correctly visited
  108. unreserveObject(hero, t1);
  109. unreserveObject(hero, t2);
  110. }
  111. else if(details.result == TryMoveHero::EMBARK && hero)
  112. {
  113. //make sure AI not attempt to visit used boat
  114. validateObject(hero->boat);
  115. }
  116. else if(details.result == TryMoveHero::DISEMBARK && o1)
  117. {
  118. auto boat = dynamic_cast<const CGBoat *>(o1);
  119. if(boat)
  120. addVisitableObj(boat);
  121. }
  122. }
  123. void VCAI::heroInGarrisonChange(const CGTownInstance * town)
  124. {
  125. LOG_TRACE(logAi);
  126. NET_EVENT_HANDLER;
  127. }
  128. void VCAI::centerView(int3 pos, int focusTime)
  129. {
  130. LOG_TRACE_PARAMS(logAi, "focusTime '%i'", focusTime);
  131. NET_EVENT_HANDLER;
  132. }
  133. void VCAI::artifactMoved(const ArtifactLocation & src, const ArtifactLocation & dst)
  134. {
  135. LOG_TRACE(logAi);
  136. NET_EVENT_HANDLER;
  137. }
  138. void VCAI::artifactAssembled(const ArtifactLocation & al)
  139. {
  140. LOG_TRACE(logAi);
  141. NET_EVENT_HANDLER;
  142. }
  143. void VCAI::showTavernWindow(const CGObjectInstance * townOrTavern)
  144. {
  145. LOG_TRACE(logAi);
  146. NET_EVENT_HANDLER;
  147. }
  148. void VCAI::showThievesGuildWindow(const CGObjectInstance * obj)
  149. {
  150. LOG_TRACE(logAi);
  151. NET_EVENT_HANDLER;
  152. }
  153. void VCAI::playerBlocked(int reason, bool start)
  154. {
  155. LOG_TRACE_PARAMS(logAi, "reason '%i', start '%i'", reason % start);
  156. NET_EVENT_HANDLER;
  157. if(start && reason == PlayerBlocked::UPCOMING_BATTLE)
  158. status.setBattle(UPCOMING_BATTLE);
  159. if(reason == PlayerBlocked::ONGOING_MOVEMENT)
  160. status.setMove(start);
  161. }
  162. void VCAI::showPuzzleMap()
  163. {
  164. LOG_TRACE(logAi);
  165. NET_EVENT_HANDLER;
  166. }
  167. void VCAI::showShipyardDialog(const IShipyard * obj)
  168. {
  169. LOG_TRACE(logAi);
  170. NET_EVENT_HANDLER;
  171. }
  172. void VCAI::gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult)
  173. {
  174. LOG_TRACE_PARAMS(logAi, "victoryLossCheckResult '%s'", victoryLossCheckResult.messageToSelf);
  175. NET_EVENT_HANDLER;
  176. logAi->debug("Player %d (%s): I heard that player %d (%s) %s.", playerID, playerID.getStr(), player, player.getStr(), (victoryLossCheckResult.victory() ? "won" : "lost"));
  177. if(player == playerID)
  178. {
  179. if(victoryLossCheckResult.victory())
  180. {
  181. logAi->debug("VCAI: I won! Incredible!");
  182. logAi->debug("Turn nr %d", myCb->getDate());
  183. }
  184. else
  185. {
  186. logAi->debug("VCAI: Player %d (%s) lost. It's me. What a disappointment! :(", player, player.getStr());
  187. }
  188. finish();
  189. }
  190. }
  191. void VCAI::artifactPut(const ArtifactLocation & al)
  192. {
  193. LOG_TRACE(logAi);
  194. NET_EVENT_HANDLER;
  195. }
  196. void VCAI::artifactRemoved(const ArtifactLocation & al)
  197. {
  198. LOG_TRACE(logAi);
  199. NET_EVENT_HANDLER;
  200. }
  201. void VCAI::artifactDisassembled(const ArtifactLocation & al)
  202. {
  203. LOG_TRACE(logAi);
  204. NET_EVENT_HANDLER;
  205. }
  206. void VCAI::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. markObjectVisited(visitedObj);
  213. unreserveObject(visitor, visitedObj);
  214. completeGoal(sptr(Goals::VisitObj(visitedObj->id.getNum()).sethero(visitor))); //we don't need to visit it anymore
  215. //TODO: what if we visited one-time visitable object that was reserved by another hero (shouldn't, but..)
  216. if (visitedObj->ID == Obj::HERO)
  217. {
  218. visitedHeroes[visitor].insert(HeroPtr(dynamic_cast<const CGHeroInstance *>(visitedObj)));
  219. }
  220. }
  221. status.heroVisit(visitedObj, start);
  222. }
  223. void VCAI::availableArtifactsChanged(const CGBlackMarket * bm)
  224. {
  225. LOG_TRACE(logAi);
  226. NET_EVENT_HANDLER;
  227. }
  228. void VCAI::heroVisitsTown(const CGHeroInstance * hero, const CGTownInstance * town)
  229. {
  230. LOG_TRACE(logAi);
  231. NET_EVENT_HANDLER;
  232. //buildArmyIn(town);
  233. //moveCreaturesToHero(town);
  234. }
  235. void VCAI::tileHidden(const std::unordered_set<int3> & pos)
  236. {
  237. LOG_TRACE(logAi);
  238. NET_EVENT_HANDLER;
  239. validateVisitableObjs();
  240. clearPathsInfo();
  241. }
  242. void VCAI::tileRevealed(const std::unordered_set<int3> & pos)
  243. {
  244. LOG_TRACE(logAi);
  245. NET_EVENT_HANDLER;
  246. for(int3 tile : pos)
  247. {
  248. for(const CGObjectInstance * obj : myCb->getVisitableObjs(tile))
  249. addVisitableObj(obj);
  250. }
  251. clearPathsInfo();
  252. }
  253. void VCAI::heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query)
  254. {
  255. LOG_TRACE(logAi);
  256. NET_EVENT_HANDLER;
  257. auto firstHero = cb->getHero(hero1);
  258. auto secondHero = cb->getHero(hero2);
  259. status.addQuery(query, boost::str(boost::format("Exchange between heroes %s (%d) and %s (%d)") % firstHero->getNameTranslated() % firstHero->tempOwner % secondHero->getNameTranslated() % secondHero->tempOwner));
  260. requestActionASAP([=]()
  261. {
  262. float goalpriority1 = 0, goalpriority2 = 0;
  263. auto firstGoal = getGoal(firstHero);
  264. if(firstGoal->goalType == Goals::GATHER_ARMY)
  265. goalpriority1 = firstGoal->priority;
  266. auto secondGoal = getGoal(secondHero);
  267. if(secondGoal->goalType == Goals::GATHER_ARMY)
  268. goalpriority2 = secondGoal->priority;
  269. auto transferFrom2to1 = [this](const CGHeroInstance * h1, const CGHeroInstance * h2) -> void
  270. {
  271. this->pickBestCreatures(h1, h2);
  272. this->pickBestArtifacts(h1, h2);
  273. };
  274. //Do not attempt army or artifacts exchange if we visited ally player
  275. //Visits can still be useful if hero have skills like Scholar
  276. if(firstHero->tempOwner != secondHero->tempOwner)
  277. {
  278. logAi->debug("Heroes owned by different players. Do not exchange army or artifacts.");
  279. }
  280. else if(goalpriority1 > goalpriority2)
  281. {
  282. transferFrom2to1(firstHero, secondHero);
  283. }
  284. else if(goalpriority1 < goalpriority2)
  285. {
  286. transferFrom2to1(secondHero, firstHero);
  287. }
  288. else //regular criteria
  289. {
  290. if(firstHero->getFightingStrength() > secondHero->getFightingStrength() && ah->canGetArmy(firstHero, secondHero))
  291. transferFrom2to1(firstHero, secondHero);
  292. else if(ah->canGetArmy(secondHero, firstHero))
  293. transferFrom2to1(secondHero, firstHero);
  294. }
  295. completeGoal(sptr(Goals::VisitHero(firstHero->id.getNum()))); //TODO: what if we were visited by other hero in the meantime?
  296. completeGoal(sptr(Goals::VisitHero(secondHero->id.getNum())));
  297. answerQuery(query, 0);
  298. });
  299. }
  300. void VCAI::heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val)
  301. {
  302. LOG_TRACE_PARAMS(logAi, "which '%i', val '%i'", which % val);
  303. NET_EVENT_HANDLER;
  304. }
  305. void VCAI::showRecruitmentDialog(const CGDwelling * dwelling, const CArmedInstance * dst, int level)
  306. {
  307. LOG_TRACE_PARAMS(logAi, "level '%i'", level);
  308. NET_EVENT_HANDLER;
  309. }
  310. void VCAI::heroMovePointsChanged(const CGHeroInstance * hero)
  311. {
  312. LOG_TRACE(logAi);
  313. NET_EVENT_HANDLER;
  314. }
  315. void VCAI::garrisonsChanged(ObjectInstanceID id1, ObjectInstanceID id2)
  316. {
  317. LOG_TRACE(logAi);
  318. NET_EVENT_HANDLER;
  319. }
  320. void VCAI::newObject(const CGObjectInstance * obj)
  321. {
  322. LOG_TRACE(logAi);
  323. NET_EVENT_HANDLER;
  324. if(obj->isVisitable())
  325. addVisitableObj(obj);
  326. }
  327. //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
  328. //see: RemoveObject::applyFirstCl, to keep AI "not cheating" do not use advantage of this and use this function just to prevent crashes
  329. void VCAI::objectRemoved(const CGObjectInstance * obj)
  330. {
  331. LOG_TRACE(logAi);
  332. NET_EVENT_HANDLER;
  333. vstd::erase_if_present(visitableObjs, obj);
  334. vstd::erase_if_present(alreadyVisited, obj);
  335. for(auto h : cb->getHeroesInfo())
  336. unreserveObject(h, obj);
  337. std::function<bool(const Goals::TSubgoal &)> checkRemovalValidity = [&](const Goals::TSubgoal & x) -> bool
  338. {
  339. if((x->goalType == Goals::VISIT_OBJ) && (x->objid == obj->id.getNum()))
  340. return true;
  341. else if(x->parent && checkRemovalValidity(x->parent)) //repeat this lambda check recursively on parent goal
  342. return true;
  343. else
  344. return false;
  345. };
  346. //clear VCAI / main loop caches
  347. vstd::erase_if(lockedHeroes, [&](const std::pair<HeroPtr, Goals::TSubgoal> & x) -> bool
  348. {
  349. return checkRemovalValidity(x.second);
  350. });
  351. vstd::erase_if(ultimateGoalsFromBasic, [&](const std::pair<Goals::TSubgoal, Goals::TGoalVec> & x) -> bool
  352. {
  353. return checkRemovalValidity(x.first);
  354. });
  355. vstd::erase_if(basicGoals, checkRemovalValidity);
  356. vstd::erase_if(goalsToAdd, checkRemovalValidity);
  357. vstd::erase_if(goalsToRemove, checkRemovalValidity);
  358. for(auto goal : ultimateGoalsFromBasic)
  359. vstd::erase_if(goal.second, checkRemovalValidity);
  360. //clear resource manager goal cache
  361. ah->removeOutdatedObjectives(checkRemovalValidity);
  362. //TODO: Find better way to handle hero boat removal
  363. if(auto hero = dynamic_cast<const CGHeroInstance *>(obj))
  364. {
  365. if(hero->boat)
  366. {
  367. vstd::erase_if_present(visitableObjs, hero->boat);
  368. vstd::erase_if_present(alreadyVisited, hero->boat);
  369. for(auto h : cb->getHeroesInfo())
  370. unreserveObject(h, hero->boat);
  371. }
  372. }
  373. //TODO
  374. //there are other places where CGObjectinstance ptrs are stored...
  375. //
  376. if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
  377. {
  378. lostHero(cb->getHero(obj->id)); //we can promote, since objectRemoved is called just before actual deletion
  379. }
  380. }
  381. void VCAI::showHillFortWindow(const CGObjectInstance * object, const CGHeroInstance * visitor)
  382. {
  383. LOG_TRACE(logAi);
  384. NET_EVENT_HANDLER;
  385. requestActionASAP([=]()
  386. {
  387. makePossibleUpgrades(visitor);
  388. });
  389. }
  390. void VCAI::playerBonusChanged(const Bonus & bonus, bool gain)
  391. {
  392. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  393. NET_EVENT_HANDLER;
  394. }
  395. void VCAI::heroCreated(const CGHeroInstance * h)
  396. {
  397. LOG_TRACE(logAi);
  398. if(h->visitedTown)
  399. townVisitsThisWeek[HeroPtr(h)].insert(h->visitedTown);
  400. NET_EVENT_HANDLER;
  401. }
  402. void VCAI::advmapSpellCast(const CGHeroInstance * caster, int spellID)
  403. {
  404. LOG_TRACE_PARAMS(logAi, "spellID '%i", spellID);
  405. NET_EVENT_HANDLER;
  406. }
  407. void VCAI::showInfoDialog(EInfoWindowMode type, const std::string & text, const std::vector<Component> & components, int soundID)
  408. {
  409. LOG_TRACE_PARAMS(logAi, "soundID '%i'", soundID);
  410. NET_EVENT_HANDLER;
  411. }
  412. void VCAI::requestRealized(PackageApplied * pa)
  413. {
  414. LOG_TRACE(logAi);
  415. NET_EVENT_HANDLER;
  416. if(status.haveTurn())
  417. {
  418. if(pa->packType == typeList.getTypeID<EndTurn>())
  419. {
  420. if(pa->result)
  421. status.madeTurn();
  422. }
  423. }
  424. if(pa->packType == typeList.getTypeID<QueryReply>())
  425. {
  426. status.receivedAnswerConfirmation(pa->requestID, pa->result);
  427. }
  428. }
  429. void VCAI::receivedResource()
  430. {
  431. LOG_TRACE(logAi);
  432. NET_EVENT_HANDLER;
  433. }
  434. void VCAI::showUniversityWindow(const IMarket * market, const CGHeroInstance * visitor)
  435. {
  436. LOG_TRACE(logAi);
  437. NET_EVENT_HANDLER;
  438. }
  439. void VCAI::heroManaPointsChanged(const CGHeroInstance * hero)
  440. {
  441. LOG_TRACE(logAi);
  442. NET_EVENT_HANDLER;
  443. }
  444. void VCAI::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  445. {
  446. LOG_TRACE_PARAMS(logAi, "which '%d', val '%d'", which % val);
  447. NET_EVENT_HANDLER;
  448. }
  449. void VCAI::battleResultsApplied()
  450. {
  451. LOG_TRACE(logAi);
  452. NET_EVENT_HANDLER;
  453. assert(status.getBattle() == ENDING_BATTLE);
  454. status.setBattle(NO_BATTLE);
  455. }
  456. void VCAI::objectPropertyChanged(const SetObjectProperty * sop)
  457. {
  458. LOG_TRACE(logAi);
  459. NET_EVENT_HANDLER;
  460. if(sop->what == ObjProperty::OWNER)
  461. {
  462. if(myCb->getPlayerRelations(playerID, (PlayerColor)sop->val) == PlayerRelations::ENEMIES)
  463. {
  464. //we want to visit objects owned by oppponents
  465. auto obj = myCb->getObj(sop->id, false);
  466. if(obj)
  467. {
  468. addVisitableObj(obj); // TODO: Remove once save compatability broken. In past owned objects were removed from this set
  469. vstd::erase_if_present(alreadyVisited, obj);
  470. }
  471. }
  472. }
  473. }
  474. void VCAI::buildChanged(const CGTownInstance * town, BuildingID buildingID, int what)
  475. {
  476. LOG_TRACE_PARAMS(logAi, "what '%i'", what);
  477. NET_EVENT_HANDLER;
  478. if(town->getOwner() == playerID && what == 1) //built
  479. completeGoal(sptr(Goals::BuildThis(buildingID, town)));
  480. }
  481. void VCAI::heroBonusChanged(const CGHeroInstance * hero, const Bonus & bonus, bool gain)
  482. {
  483. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  484. NET_EVENT_HANDLER;
  485. }
  486. void VCAI::showMarketWindow(const IMarket * market, const CGHeroInstance * visitor)
  487. {
  488. LOG_TRACE(logAi);
  489. NET_EVENT_HANDLER;
  490. }
  491. void VCAI::showWorldViewEx(const std::vector<ObjectPosInfo> & objectPositions, bool showTerrain)
  492. {
  493. //TODO: AI support for ViewXXX spell
  494. LOG_TRACE(logAi);
  495. NET_EVENT_HANDLER;
  496. }
  497. void VCAI::initGameInterface(std::shared_ptr<Environment> ENV, std::shared_ptr<CCallback> CB)
  498. {
  499. LOG_TRACE(logAi);
  500. env = ENV;
  501. myCb = CB;
  502. cbc = CB;
  503. ah->init(CB.get());
  504. NET_EVENT_HANDLER; //sets ah->rm->cb
  505. playerID = *myCb->getMyColor();
  506. myCb->waitTillRealize = true;
  507. myCb->unlockGsWhenWaiting = true;
  508. if(!fh)
  509. fh = new FuzzyHelper();
  510. retrieveVisitableObjs();
  511. }
  512. void VCAI::yourTurn()
  513. {
  514. LOG_TRACE(logAi);
  515. NET_EVENT_HANDLER;
  516. status.startedTurn();
  517. makingTurn = std::make_unique<boost::thread>(&VCAI::makeTurn, this);
  518. }
  519. void VCAI::heroGotLevel(const CGHeroInstance * hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill> & skills, QueryID queryID)
  520. {
  521. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  522. NET_EVENT_HANDLER;
  523. status.addQuery(queryID, boost::str(boost::format("Hero %s got level %d") % hero->getNameTranslated() % hero->level));
  524. requestActionASAP([=](){ answerQuery(queryID, 0); });
  525. }
  526. void VCAI::commanderGotLevel(const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID)
  527. {
  528. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  529. NET_EVENT_HANDLER;
  530. status.addQuery(queryID, boost::str(boost::format("Commander %s of %s got level %d") % commander->name % commander->armyObj->nodeName() % (int)commander->level));
  531. requestActionASAP([=](){ answerQuery(queryID, 0); });
  532. }
  533. void VCAI::showBlockingDialog(const std::string & text, const std::vector<Component> & components, QueryID askID, const int soundID, bool selection, bool cancel)
  534. {
  535. LOG_TRACE_PARAMS(logAi, "text '%s', askID '%i', soundID '%i', selection '%i', cancel '%i'", text % askID % soundID % selection % cancel);
  536. NET_EVENT_HANDLER;
  537. int sel = 0;
  538. status.addQuery(askID, boost::str(boost::format("Blocking dialog query with %d components - %s")
  539. % components.size() % text));
  540. if(selection) //select from multiple components -> take the last one (they're indexed [1-size])
  541. sel = static_cast<int>(components.size());
  542. if(!selection && cancel) //yes&no -> always answer yes, we are a brave AI :)
  543. sel = 1;
  544. requestActionASAP([=]()
  545. {
  546. answerQuery(askID, sel);
  547. });
  548. }
  549. void VCAI::showTeleportDialog(TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID)
  550. {
  551. // LOG_TRACE_PARAMS(logAi, "askID '%i', exits '%s'", askID % exits);
  552. NET_EVENT_HANDLER;
  553. status.addQuery(askID, boost::str(boost::format("Teleport dialog query with %d exits")
  554. % exits.size()));
  555. int choosenExit = -1;
  556. if(impassable)
  557. {
  558. knownTeleportChannels[channel]->passability = TeleportChannel::IMPASSABLE;
  559. }
  560. else if(destinationTeleport != ObjectInstanceID() && destinationTeleportPos.valid())
  561. {
  562. auto neededExit = std::make_pair(destinationTeleport, destinationTeleportPos);
  563. if(destinationTeleport != ObjectInstanceID() && vstd::contains(exits, neededExit))
  564. choosenExit = vstd::find_pos(exits, neededExit);
  565. }
  566. for(auto exit : exits)
  567. {
  568. if(status.channelProbing() && exit.first == destinationTeleport)
  569. {
  570. choosenExit = vstd::find_pos(exits, exit);
  571. break;
  572. }
  573. else
  574. {
  575. // TODO: Implement checking if visiting that teleport will uncovert any FoW
  576. // So far this is the best option to handle decision about probing
  577. auto obj = cb->getObj(exit.first, false);
  578. if(obj == nullptr && !vstd::contains(teleportChannelProbingList, exit.first))
  579. {
  580. if(exit.first != destinationTeleport)
  581. teleportChannelProbingList.push_back(exit.first);
  582. }
  583. }
  584. }
  585. requestActionASAP([=]()
  586. {
  587. answerQuery(askID, choosenExit);
  588. });
  589. }
  590. void VCAI::showGarrisonDialog(const CArmedInstance * up, const CGHeroInstance * down, bool removableUnits, QueryID queryID)
  591. {
  592. LOG_TRACE_PARAMS(logAi, "removableUnits '%i', queryID '%i'", removableUnits % queryID);
  593. NET_EVENT_HANDLER;
  594. std::string s1 = up ? up->nodeName() : "NONE";
  595. std::string s2 = down ? down->nodeName() : "NONE";
  596. status.addQuery(queryID, boost::str(boost::format("Garrison dialog with %s and %s") % s1 % s2));
  597. //you can't request action from action-response thread
  598. requestActionASAP([=]()
  599. {
  600. if(removableUnits)
  601. pickBestCreatures(down, up);
  602. answerQuery(queryID, 0);
  603. });
  604. }
  605. void VCAI::showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects)
  606. {
  607. NET_EVENT_HANDLER;
  608. status.addQuery(askID, "Map object select query");
  609. requestActionASAP([=](){ answerQuery(askID, selectedObject.getNum()); });
  610. }
  611. void VCAI::saveGame(BinarySerializer & h, const int version)
  612. {
  613. LOG_TRACE_PARAMS(logAi, "version '%i'", version);
  614. NET_EVENT_HANDLER;
  615. validateVisitableObjs();
  616. #if 0
  617. //disabled due to issue 2890
  618. registerGoals(h);
  619. #endif // 0
  620. CAdventureAI::saveGame(h, version);
  621. serializeInternal(h, version);
  622. }
  623. void VCAI::loadGame(BinaryDeserializer & h, const int version)
  624. {
  625. LOG_TRACE_PARAMS(logAi, "version '%i'", version);
  626. //NET_EVENT_HANDLER;
  627. #if 0
  628. //disabled due to issue 2890
  629. registerGoals(h);
  630. #endif // 0
  631. CAdventureAI::loadGame(h, version);
  632. serializeInternal(h, version);
  633. }
  634. void makePossibleUpgrades(const CArmedInstance * obj)
  635. {
  636. if(!obj)
  637. return;
  638. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  639. {
  640. if(const CStackInstance * s = obj->getStackPtr(SlotID(i)))
  641. {
  642. UpgradeInfo ui;
  643. cb->fillUpgradeInfo(obj, SlotID(i), ui);
  644. if(ui.oldID >= 0 && cb->getResourceAmount().canAfford(ui.cost[0] * s->count))
  645. {
  646. cb->upgradeCreature(obj, SlotID(i), ui.newID[0]);
  647. }
  648. }
  649. }
  650. }
  651. void VCAI::makeTurn()
  652. {
  653. MAKING_TURN;
  654. auto day = cb->getDate(Date::EDateType::DAY);
  655. logAi->info("Player %d (%s) starting turn, day %d", playerID, playerID.getStr(), day);
  656. boost::shared_lock<boost::shared_mutex> gsLock(CGameState::mutex);
  657. setThreadName("VCAI::makeTurn");
  658. switch(cb->getDate(Date::DAY_OF_WEEK))
  659. {
  660. case 1:
  661. {
  662. townVisitsThisWeek.clear();
  663. std::vector<const CGObjectInstance *> objs;
  664. retrieveVisitableObjs(objs, true);
  665. for(const CGObjectInstance * obj : objs)
  666. {
  667. if(isWeeklyRevisitable(obj))
  668. {
  669. addVisitableObj(obj);
  670. vstd::erase_if_present(alreadyVisited, obj);
  671. }
  672. }
  673. break;
  674. }
  675. }
  676. markHeroAbleToExplore(primaryHero());
  677. visitedHeroes.clear();
  678. try
  679. {
  680. //it looks messy here, but it's better to have armed heroes before attempting realizing goals
  681. for (const CGTownInstance * t : cb->getTownsInfo())
  682. moveCreaturesToHero(t);
  683. mainLoop();
  684. /*Below function is also responsible for hero movement via internal wander function. By design it is separate logic for heroes that have nothing to do.
  685. Heroes that were not picked by striveToGoal(sptr(Goals::Win())); recently (so they do not have new goals and cannot continue/reevaluate previously locked goals) will do logic in wander().*/
  686. performTypicalActions();
  687. //for debug purpose
  688. for (auto h : cb->getHeroesInfo())
  689. {
  690. if (h->movement)
  691. logAi->warn("Hero %s has %d MP left", h->getNameTranslated(), h->movement);
  692. }
  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. endTurn();
  705. }
  706. std::vector<HeroPtr> VCAI::getMyHeroes() const
  707. {
  708. std::vector<HeroPtr> ret;
  709. for(auto h : cb->getHeroesInfo())
  710. {
  711. ret.push_back(h);
  712. }
  713. return ret;
  714. }
  715. void VCAI::mainLoop()
  716. {
  717. std::vector<Goals::TSubgoal> elementarGoals; //no duplicates allowed (operator ==)
  718. basicGoals.clear();
  719. validateVisitableObjs();
  720. //get all potential and saved goals
  721. //TODO: not lose
  722. basicGoals.push_back(sptr(Goals::Win()));
  723. for (auto goalPair : lockedHeroes)
  724. {
  725. fh->setPriority(goalPair.second); //re-evaluate, as heroes moved in the meantime
  726. basicGoals.push_back(goalPair.second);
  727. }
  728. if (ah->hasTasksLeft())
  729. basicGoals.push_back(ah->whatToDo());
  730. for (auto quest : myCb->getMyQuests())
  731. {
  732. basicGoals.push_back(sptr(Goals::CompleteQuest(quest)));
  733. }
  734. basicGoals.push_back(sptr(Goals::Build()));
  735. invalidPathHeroes.clear();
  736. for (int pass = 0; pass< 30 && basicGoals.size(); pass++)
  737. {
  738. vstd::removeDuplicates(basicGoals); //TODO: container which does this automagically without has would be nice
  739. goalsToAdd.clear();
  740. goalsToRemove.clear();
  741. elementarGoals.clear();
  742. ultimateGoalsFromBasic.clear();
  743. ah->updatePaths(getMyHeroes());
  744. logAi->debug("Main loop: decomposing %i basic goals", basicGoals.size());
  745. for (auto basicGoal : basicGoals)
  746. {
  747. logAi->debug("Main loop: decomposing basic goal %s", basicGoal->name());
  748. auto goalToDecompose = basicGoal;
  749. Goals::TSubgoal elementarGoal = sptr(Goals::Invalid());
  750. int maxAbstractGoals = 10;
  751. while (!elementarGoal->isElementar && maxAbstractGoals)
  752. {
  753. try
  754. {
  755. elementarGoal = decomposeGoal(goalToDecompose);
  756. }
  757. catch (goalFulfilledException & e)
  758. {
  759. //it is impossible to continue some goals (like exploration, for example)
  760. //complete abstract goal for now, but maybe main goal finds another path
  761. logAi->debug("Goal %s decomposition failed: goal was completed as much as possible", e.goal->name());
  762. completeGoal(e.goal); //put in goalsToRemove
  763. break;
  764. }
  765. catch(cannotFulfillGoalException & e)
  766. {
  767. //it is impossible to continue some goals (like exploration, for example)
  768. //complete abstract goal for now, but maybe main goal finds another path
  769. goalsToRemove.push_back(basicGoal);
  770. logAi->debug("Goal %s decomposition failed: %s", goalToDecompose->name(), e.what());
  771. break;
  772. }
  773. catch (std::exception & e) //decomposition failed, which means we can't decompose entire tree
  774. {
  775. goalsToRemove.push_back(basicGoal);
  776. logAi->debug("Goal %s decomposition failed: %s", basicGoal->name(), e.what());
  777. break;
  778. }
  779. if (elementarGoal->isAbstract) //we can decompose it further
  780. {
  781. goalsToAdd.push_back(elementarGoal);
  782. //decompose further now - this is necesssary if we can't add over 10 goals in the pool
  783. goalToDecompose = elementarGoal;
  784. //there is a risk of infinite abstract goal loop, though it indicates failed logic
  785. maxAbstractGoals--;
  786. }
  787. else if (elementarGoal->isElementar) //should be
  788. {
  789. logAi->debug("Found elementar goal %s", elementarGoal->name());
  790. elementarGoals.push_back(elementarGoal);
  791. ultimateGoalsFromBasic[elementarGoal].push_back(goalToDecompose); //TODO: how about indirect basicGoal?
  792. break;
  793. }
  794. else //should never be here
  795. throw cannotFulfillGoalException("Goal %s is neither abstract nor elementar!" + basicGoal->name());
  796. }
  797. }
  798. logAi->trace("Main loop: selecting best elementar goal");
  799. //now choose one elementar goal to realize
  800. Goals::TGoalVec possibleGoals(elementarGoals.begin(), elementarGoals.end()); //copy to vector
  801. Goals::TSubgoal goalToRealize = sptr(Goals::Invalid());
  802. while (possibleGoals.size())
  803. {
  804. //allow assign goals to heroes with 0 movement, but don't realize them
  805. //maybe there are beter ones left
  806. auto bestGoal = fh->chooseSolution(possibleGoals);
  807. if (bestGoal->hero) //lock this hero to fulfill goal
  808. {
  809. setGoal(bestGoal->hero, bestGoal);
  810. if (!bestGoal->hero->movement || vstd::contains(invalidPathHeroes, bestGoal->hero))
  811. {
  812. if (!vstd::erase_if_present(possibleGoals, bestGoal))
  813. {
  814. logAi->error("erase_if_preset failed? Something very wrong!");
  815. break;
  816. }
  817. continue; //chose next from the list
  818. }
  819. }
  820. goalToRealize = bestGoal; //we found our goal to execute
  821. break;
  822. }
  823. //realize best goal
  824. if (!goalToRealize->invalid())
  825. {
  826. logAi->debug("Trying to realize %s (value %2.3f)", goalToRealize->name(), goalToRealize->priority);
  827. try
  828. {
  829. boost::this_thread::interruption_point();
  830. goalToRealize->accept(this); //visitor pattern
  831. boost::this_thread::interruption_point();
  832. }
  833. catch (boost::thread_interrupted & e)
  834. {
  835. (void)e;
  836. logAi->debug("Player %d: Making turn thread received an interruption!", playerID);
  837. throw; //rethrow, we want to truly end this thread
  838. }
  839. catch (goalFulfilledException & e)
  840. {
  841. //the sub-goal was completed successfully
  842. completeGoal(e.goal);
  843. //local goal was also completed?
  844. completeGoal(goalToRealize);
  845. // remove abstract visit tile if we completed the elementar one
  846. vstd::erase_if_present(goalsToAdd, goalToRealize);
  847. }
  848. catch (std::exception & e)
  849. {
  850. logAi->debug("Failed to realize subgoal of type %s, I will stop.", goalToRealize->name());
  851. logAi->debug("The error message was: %s", e.what());
  852. //erase base goal if we failed to execute decomposed goal
  853. for (auto basicGoal : ultimateGoalsFromBasic[goalToRealize])
  854. goalsToRemove.push_back(basicGoal);
  855. // sometimes resource manager contains an elementar goal which is not able to execute anymore and just fails each turn.
  856. ai->ah->notifyGoalCompleted(goalToRealize);
  857. //we failed to realize best goal, but maybe others are still possible?
  858. }
  859. //remove goals we couldn't decompose
  860. for (auto goal : goalsToRemove)
  861. vstd::erase_if_present(basicGoals, goal);
  862. //add abstract goals
  863. boost::sort(goalsToAdd, [](const Goals::TSubgoal & lhs, const Goals::TSubgoal & rhs) -> bool
  864. {
  865. return lhs->priority > rhs->priority; //highest priority at the beginning
  866. });
  867. //max number of goals = 10
  868. int i = 0;
  869. while (basicGoals.size() < 10 && goalsToAdd.size() > i)
  870. {
  871. if (!vstd::contains(basicGoals, goalsToAdd[i])) //don't add duplicates
  872. basicGoals.push_back(goalsToAdd[i]);
  873. i++;
  874. }
  875. }
  876. else //no elementar goals possible
  877. {
  878. logAi->debug("Goal decomposition exhausted");
  879. break;
  880. }
  881. }
  882. }
  883. void VCAI::performObjectInteraction(const CGObjectInstance * obj, HeroPtr h)
  884. {
  885. LOG_TRACE_PARAMS(logAi, "Hero %s and object %s at %s", h->getNameTranslated() % obj->getObjectName() % obj->pos.toString());
  886. switch(obj->ID)
  887. {
  888. case Obj::CREATURE_GENERATOR1:
  889. recruitCreatures(dynamic_cast<const CGDwelling *>(obj), h.get());
  890. checkHeroArmy(h);
  891. break;
  892. case Obj::TOWN:
  893. moveCreaturesToHero(dynamic_cast<const CGTownInstance *>(obj));
  894. if(h->visitedTown) //we are inside, not just attacking
  895. {
  896. townVisitsThisWeek[h].insert(h->visitedTown);
  897. if(!h->hasSpellbook() && ah->freeGold() >= GameConstants::SPELLBOOK_GOLD_COST)
  898. {
  899. if(h->visitedTown->hasBuilt(BuildingID::MAGES_GUILD_1))
  900. cb->buyArtifact(h.get(), ArtifactID::SPELLBOOK);
  901. }
  902. }
  903. break;
  904. }
  905. completeGoal(sptr(Goals::VisitObj(obj->id.getNum()).sethero(h)));
  906. }
  907. void VCAI::moveCreaturesToHero(const CGTownInstance * t)
  908. {
  909. if(t->visitingHero && t->armedGarrison() && t->visitingHero->tempOwner == t->tempOwner)
  910. {
  911. pickBestCreatures(t->visitingHero, t);
  912. }
  913. }
  914. void VCAI::pickBestCreatures(const CArmedInstance * destinationArmy, const CArmedInstance * source)
  915. {
  916. const CArmedInstance * armies[] = {destinationArmy, source};
  917. auto bestArmy = ah->getSortedSlots(destinationArmy, source);
  918. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  919. for(SlotID i = SlotID(0); i.getNum() < bestArmy.size() && i.validSlot(); i.advance(1)) //i-th strongest creature type will go to i-th slot
  920. {
  921. const CCreature * targetCreature = bestArmy[i.getNum()].creature;
  922. for(auto armyPtr : armies)
  923. {
  924. for(SlotID j = SlotID(0); j.validSlot(); j.advance(1))
  925. {
  926. if(armyPtr->getCreature(j) == targetCreature && (i != j || armyPtr != destinationArmy)) //it's a searched creature not in dst SLOT
  927. {
  928. //can't take away last creature without split. generate a new stack with 1 creature which is weak but fast
  929. if(armyPtr == source
  930. && source->needsLastStack()
  931. && source->stacksCount() == 1
  932. && (!destinationArmy->hasStackAtSlot(i) || destinationArmy->getCreature(i) == targetCreature))
  933. {
  934. auto weakest = ah->getWeakestCreature(bestArmy);
  935. if(weakest->creature == targetCreature)
  936. {
  937. if(1 == source->getStackCount(j))
  938. break;
  939. // move all except 1 of weakest creature from source to destination
  940. cb->splitStack(
  941. source,
  942. destinationArmy,
  943. j,
  944. destinationArmy->getSlotFor(targetCreature),
  945. destinationArmy->getStackCount(i) + source->getStackCount(j) - 1);
  946. break;
  947. }
  948. else
  949. {
  950. // Source last stack is not weakest. Move 1 of weakest creature from destination to source
  951. cb->splitStack(
  952. destinationArmy,
  953. source,
  954. destinationArmy->getSlotFor(weakest->creature),
  955. source->getFreeSlot(),
  956. 1);
  957. }
  958. }
  959. cb->mergeOrSwapStacks(armyPtr, destinationArmy, j, i);
  960. }
  961. }
  962. }
  963. }
  964. //TODO - having now strongest possible army, we may want to think about arranging stacks
  965. auto hero = dynamic_cast<const CGHeroInstance *>(destinationArmy);
  966. if(hero)
  967. checkHeroArmy(hero);
  968. }
  969. void VCAI::pickBestArtifacts(const CGHeroInstance * h, const CGHeroInstance * other)
  970. {
  971. auto equipBest = [](const CGHeroInstance * h, const CGHeroInstance * otherh, bool giveStuffToFirstHero) -> void
  972. {
  973. bool changeMade = false;
  974. do
  975. {
  976. changeMade = false;
  977. //we collect gear always in same order
  978. std::vector<ArtifactLocation> allArtifacts;
  979. if(giveStuffToFirstHero)
  980. {
  981. for(auto p : h->artifactsWorn)
  982. {
  983. if(p.second.artifact)
  984. allArtifacts.push_back(ArtifactLocation(h, p.first));
  985. }
  986. }
  987. for(auto slot : h->artifactsInBackpack)
  988. allArtifacts.push_back(ArtifactLocation(h, h->getArtPos(slot.artifact)));
  989. if(otherh)
  990. {
  991. for(auto p : otherh->artifactsWorn)
  992. {
  993. if(p.second.artifact)
  994. allArtifacts.push_back(ArtifactLocation(otherh, p.first));
  995. }
  996. for(auto slot : otherh->artifactsInBackpack)
  997. allArtifacts.push_back(ArtifactLocation(otherh, otherh->getArtPos(slot.artifact)));
  998. }
  999. //we give stuff to one hero or another, depending on giveStuffToFirstHero
  1000. const CGHeroInstance * target = nullptr;
  1001. if(giveStuffToFirstHero || !otherh)
  1002. target = h;
  1003. else
  1004. target = otherh;
  1005. for(auto location : allArtifacts)
  1006. {
  1007. if(location.slot == ArtifactPosition::MACH4 || location.slot == ArtifactPosition::SPELLBOOK)
  1008. continue; // don't attempt to move catapult and spellbook
  1009. if(location.relatedObj() == target && location.slot < ArtifactPosition::AFTER_LAST)
  1010. continue; //don't reequip artifact we already wear
  1011. auto s = location.getSlot();
  1012. if(!s || s->locked) //we can't move locks
  1013. continue;
  1014. auto artifact = s->artifact;
  1015. if(!artifact)
  1016. continue;
  1017. //FIXME: why are the above possible to be null?
  1018. bool emptySlotFound = false;
  1019. for(auto slot : artifact->artType->possibleSlots.at(target->bearerType()))
  1020. {
  1021. ArtifactLocation destLocation(target, slot);
  1022. if(target->isPositionFree(slot) && artifact->canBePutAt(destLocation, true)) //combined artifacts are not always allowed to move
  1023. {
  1024. cb->swapArtifacts(location, destLocation); //just put into empty slot
  1025. emptySlotFound = true;
  1026. changeMade = true;
  1027. break;
  1028. }
  1029. }
  1030. if(!emptySlotFound) //try to put that atifact in already occupied slot
  1031. {
  1032. for(auto slot : artifact->artType->possibleSlots.at(target->bearerType()))
  1033. {
  1034. auto otherSlot = target->getSlot(slot);
  1035. if(otherSlot && otherSlot->artifact) //we need to exchange artifact for better one
  1036. {
  1037. ArtifactLocation destLocation(target, slot);
  1038. //if that artifact is better than what we have, pick it
  1039. if(compareArtifacts(artifact, otherSlot->artifact) && artifact->canBePutAt(destLocation, true)) //combined artifacts are not always allowed to move
  1040. {
  1041. cb->swapArtifacts(location, ArtifactLocation(target, target->getArtPos(otherSlot->artifact)));
  1042. changeMade = true;
  1043. break;
  1044. }
  1045. }
  1046. }
  1047. }
  1048. if(changeMade)
  1049. break; //start evaluating artifacts from scratch
  1050. }
  1051. }
  1052. while(changeMade);
  1053. };
  1054. equipBest(h, other, true);
  1055. if(other)
  1056. equipBest(h, other, false);
  1057. }
  1058. void VCAI::recruitCreatures(const CGDwelling * d, const CArmedInstance * recruiter)
  1059. {
  1060. //now used only for visited dwellings / towns, not BuyArmy goal
  1061. for(int i = 0; i < d->creatures.size(); i++)
  1062. {
  1063. if(!d->creatures[i].second.size())
  1064. continue;
  1065. int count = d->creatures[i].first;
  1066. CreatureID creID = d->creatures[i].second.back();
  1067. vstd::amin(count, ah->freeResources() / VLC->creatures()->getById(creID)->getFullRecruitCost());
  1068. if(count > 0)
  1069. cb->recruitCreatures(d, recruiter, creID, count, i);
  1070. }
  1071. }
  1072. bool VCAI::isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, std::optional<float> movementCostLimit)
  1073. {
  1074. int3 op = obj->visitablePos();
  1075. auto paths = ah->getPathsToTile(h, op);
  1076. for(const auto & path : paths)
  1077. {
  1078. if(movementCostLimit && movementCostLimit.value() < path.movementCost())
  1079. return false;
  1080. if(isGoodForVisit(obj, h, path))
  1081. return true;
  1082. }
  1083. return false;
  1084. }
  1085. bool VCAI::isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, const AIPath & path) const
  1086. {
  1087. const int3 pos = obj->visitablePos();
  1088. const int3 targetPos = path.firstTileToGet();
  1089. if (!targetPos.valid())
  1090. return false;
  1091. if (!isTileNotReserved(h.get(), targetPos))
  1092. return false;
  1093. if (obj->wasVisited(playerID))
  1094. return false;
  1095. if (cb->getPlayerRelations(playerID, obj->tempOwner) != PlayerRelations::ENEMIES && !isWeeklyRevisitable(obj))
  1096. return false; // Otherwise we flag or get weekly resources / creatures
  1097. if (!isSafeToVisit(h, pos))
  1098. return false;
  1099. if (!shouldVisit(h, obj))
  1100. return false;
  1101. if (vstd::contains(alreadyVisited, obj))
  1102. return false;
  1103. if (vstd::contains(reservedObjs, obj))
  1104. return false;
  1105. // TODO: looks extra if we already have AIPath
  1106. //if (!isAccessibleForHero(targetPos, h))
  1107. // return false;
  1108. const CGObjectInstance * topObj = cb->getVisitableObjs(obj->visitablePos()).back(); //it may be hero visiting this obj
  1109. //we don't try visiting object on which allied or owned hero stands
  1110. // -> it will just trigger exchange windows and AI will be confused that obj behind doesn't get visited
  1111. return !(topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES); //all of the following is met
  1112. }
  1113. bool VCAI::isTileNotReserved(const CGHeroInstance * h, int3 t) const
  1114. {
  1115. if(t.valid())
  1116. {
  1117. auto obj = cb->getTopObj(t);
  1118. if(obj && vstd::contains(ai->reservedObjs, obj)
  1119. && vstd::contains(reservedHeroesMap, h)
  1120. && !vstd::contains(reservedHeroesMap.at(h), obj))
  1121. return false; //do not capture object reserved by another hero
  1122. else
  1123. return true;
  1124. }
  1125. else
  1126. {
  1127. return false;
  1128. }
  1129. }
  1130. bool VCAI::canRecruitAnyHero(const CGTownInstance * t) const
  1131. {
  1132. //TODO: make gathering gold, building tavern or conquering town (?) possible subgoals
  1133. if(!t)
  1134. t = findTownWithTavern();
  1135. if(!t)
  1136. return false;
  1137. if(cb->getResourceAmount(EGameResID::GOLD) < GameConstants::HERO_GOLD_COST) //TODO: use ResourceManager
  1138. return false;
  1139. if(cb->getHeroesInfo().size() >= ALLOWED_ROAMING_HEROES)
  1140. return false;
  1141. if(cb->getHeroesInfo().size() >= VLC->settings()->getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP))
  1142. return false;
  1143. if(!cb->getAvailableHeroes(t).size())
  1144. return false;
  1145. return true;
  1146. }
  1147. void VCAI::wander(HeroPtr h)
  1148. {
  1149. auto visitTownIfAny = [this](HeroPtr h) -> bool
  1150. {
  1151. if (h->visitedTown)
  1152. {
  1153. townVisitsThisWeek[h].insert(h->visitedTown);
  1154. buildArmyIn(h->visitedTown);
  1155. return true;
  1156. }
  1157. return false;
  1158. };
  1159. //unclaim objects that are now dangerous for us
  1160. auto reservedObjsSetCopy = reservedHeroesMap[h];
  1161. for(auto obj : reservedObjsSetCopy)
  1162. {
  1163. if(!isSafeToVisit(h, obj->visitablePos()))
  1164. unreserveObject(h, obj);
  1165. }
  1166. TimeCheck tc("looking for wander destination");
  1167. while(h->movement)
  1168. {
  1169. validateVisitableObjs();
  1170. ah->updatePaths(getMyHeroes());
  1171. std::vector<ObjectIdRef> dests;
  1172. //also visit our reserved objects - but they are not prioritized to avoid running back and forth
  1173. vstd::copy_if(reservedHeroesMap[h], std::back_inserter(dests), [&](ObjectIdRef obj) -> bool
  1174. {
  1175. return ah->isTileAccessible(h, obj->visitablePos());
  1176. });
  1177. int pass = 0;
  1178. std::vector<std::optional<float>> distanceLimits = {1.0, 2.0, std::nullopt};
  1179. while(!dests.size() && pass < distanceLimits.size())
  1180. {
  1181. auto & distanceLimit = distanceLimits[pass];
  1182. logAi->debug("Looking for wander destination pass=%i, cost limit=%f", pass, distanceLimit.value_or(-1.0));
  1183. vstd::copy_if(visitableObjs, std::back_inserter(dests), [&](ObjectIdRef obj) -> bool
  1184. {
  1185. return isGoodForVisit(obj, h, distanceLimit);
  1186. });
  1187. pass++;
  1188. }
  1189. if(!dests.size())
  1190. {
  1191. logAi->debug("Looking for town destination");
  1192. if(cb->getVisitableObjs(h->visitablePos()).size() > 1)
  1193. moveHeroToTile(h->visitablePos(), h); //just in case we're standing on blocked subterranean gate
  1194. auto compareReinforcements = [&](const CGTownInstance * lhs, const CGTownInstance * rhs) -> bool
  1195. {
  1196. const CGHeroInstance * hptr = h.get();
  1197. auto r1 = ah->howManyReinforcementsCanGet(hptr, lhs),
  1198. r2 = ah->howManyReinforcementsCanGet(hptr, rhs);
  1199. if (r1 != r2)
  1200. return r1 < r2;
  1201. else
  1202. return ah->howManyReinforcementsCanBuy(hptr, lhs) < ah->howManyReinforcementsCanBuy(hptr, rhs);
  1203. };
  1204. std::vector<const CGTownInstance *> townsReachable;
  1205. std::vector<const CGTownInstance *> townsNotReachable;
  1206. for(const CGTownInstance * t : cb->getTownsInfo())
  1207. {
  1208. if(!t->visitingHero && !vstd::contains(townVisitsThisWeek[h], t))
  1209. {
  1210. if(isAccessibleForHero(t->visitablePos(), h))
  1211. townsReachable.push_back(t);
  1212. else
  1213. townsNotReachable.push_back(t);
  1214. }
  1215. }
  1216. if(townsReachable.size()) //travel to town with largest garrison, or empty - better than nothing
  1217. {
  1218. dests.push_back(*boost::max_element(townsReachable, compareReinforcements));
  1219. }
  1220. else if(townsNotReachable.size())
  1221. {
  1222. //TODO pick the truly best
  1223. const CGTownInstance * t = *boost::max_element(townsNotReachable, compareReinforcements);
  1224. logAi->debug("%s can't reach any town, we'll try to make our way to %s at %s", h->getNameTranslated(), t->getNameTranslated(), t->visitablePos().toString());
  1225. int3 pos1 = h->pos;
  1226. striveToGoal(sptr(Goals::ClearWayTo(t->visitablePos()).sethero(h))); //TODO: drop "strive", add to mainLoop
  1227. //if out hero is stuck, we may need to request another hero to clear the way we see
  1228. if(pos1 == h->pos && h == primaryHero()) //hero can't move
  1229. {
  1230. if(canRecruitAnyHero(t))
  1231. recruitHero(t);
  1232. }
  1233. break;
  1234. }
  1235. else if(cb->getResourceAmount(EGameResID::GOLD) >= GameConstants::HERO_GOLD_COST)
  1236. {
  1237. std::vector<const CGTownInstance *> towns = cb->getTownsInfo();
  1238. vstd::erase_if(towns, [&](const CGTownInstance * t) -> bool
  1239. {
  1240. for(const CGHeroInstance * h : cb->getHeroesInfo())
  1241. {
  1242. if(!t->getArmyStrength() || ah->howManyReinforcementsCanGet(h, t))
  1243. return true;
  1244. }
  1245. return false;
  1246. });
  1247. if (towns.size())
  1248. {
  1249. recruitHero(*boost::max_element(towns, compareArmyStrength));
  1250. }
  1251. break;
  1252. }
  1253. else
  1254. {
  1255. logAi->debug("Nowhere more to go...");
  1256. break;
  1257. }
  1258. }
  1259. //end of objs empty
  1260. if(dests.size()) //performance improvement
  1261. {
  1262. Goals::TGoalVec targetObjectGoals;
  1263. for(auto destination : dests)
  1264. {
  1265. vstd::concatenate(targetObjectGoals, ah->howToVisitObj(h, destination, false));
  1266. }
  1267. if(targetObjectGoals.size())
  1268. {
  1269. auto bestObjectGoal = fh->chooseSolution(targetObjectGoals);
  1270. //wander should not cause heroes to be reserved - they are always considered free
  1271. if(bestObjectGoal->goalType == Goals::VISIT_OBJ)
  1272. {
  1273. auto chosenObject = cb->getObjInstance(ObjectInstanceID(bestObjectGoal->objid));
  1274. if(chosenObject != nullptr)
  1275. logAi->debug("Of all %d destinations, object %s at pos=%s seems nice", dests.size(), chosenObject->getObjectName(), chosenObject->pos.toString());
  1276. }
  1277. else
  1278. logAi->debug("Trying to realize goal of type %s as part of wandering.", bestObjectGoal->name());
  1279. try
  1280. {
  1281. decomposeGoal(bestObjectGoal)->accept(this);
  1282. }
  1283. catch(const goalFulfilledException & e)
  1284. {
  1285. if(e.goal->goalType == Goals::EGoals::VISIT_TILE || e.goal->goalType == Goals::EGoals::VISIT_OBJ)
  1286. continue;
  1287. throw e;
  1288. }
  1289. }
  1290. else
  1291. {
  1292. logAi->debug("Nowhere more to go...");
  1293. break;
  1294. }
  1295. visitTownIfAny(h);
  1296. }
  1297. }
  1298. visitTownIfAny(h); //in case hero is just sitting in town
  1299. }
  1300. void VCAI::setGoal(HeroPtr h, Goals::TSubgoal goal)
  1301. {
  1302. if(goal->invalid())
  1303. {
  1304. vstd::erase_if_present(lockedHeroes, h);
  1305. }
  1306. else
  1307. {
  1308. lockedHeroes[h] = goal;
  1309. goal->setisElementar(false); //Force always evaluate goals before realizing
  1310. }
  1311. }
  1312. void VCAI::evaluateGoal(HeroPtr h)
  1313. {
  1314. if(vstd::contains(lockedHeroes, h))
  1315. fh->setPriority(lockedHeroes[h]);
  1316. }
  1317. void VCAI::completeGoal(Goals::TSubgoal goal)
  1318. {
  1319. if (goal->goalType == Goals::WIN) //we can never complete this goal - unless we already won
  1320. return;
  1321. logAi->debug("Completing goal: %s", goal->name());
  1322. //notify Managers
  1323. ah->notifyGoalCompleted(goal);
  1324. //notify mainLoop()
  1325. goalsToRemove.push_back(goal); //will be removed from mainLoop() goals
  1326. for (auto basicGoal : basicGoals) //we could luckily fulfill any of our goals
  1327. {
  1328. if (basicGoal->fulfillsMe(goal))
  1329. goalsToRemove.push_back(basicGoal);
  1330. }
  1331. //unreserve heroes
  1332. if(const CGHeroInstance * h = goal->hero.get(true))
  1333. {
  1334. auto it = lockedHeroes.find(h);
  1335. if(it != lockedHeroes.end())
  1336. {
  1337. if(it->second == goal || it->second->fulfillsMe(goal)) //FIXME this is overspecified, fulfillsMe shoudl be complete
  1338. {
  1339. logAi->debug(goal->completeMessage());
  1340. lockedHeroes.erase(it); //goal fulfilled, free hero
  1341. }
  1342. }
  1343. }
  1344. else //complete goal for all heroes maybe?
  1345. {
  1346. vstd::erase_if(lockedHeroes, [goal](std::pair<HeroPtr, Goals::TSubgoal> p)
  1347. {
  1348. if(p.second == goal || p.second->fulfillsMe(goal)) //we could have fulfilled goals of other heroes by chance
  1349. {
  1350. logAi->debug(p.second->completeMessage());
  1351. return true;
  1352. }
  1353. return false;
  1354. });
  1355. }
  1356. }
  1357. void VCAI::battleStart(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool side)
  1358. {
  1359. NET_EVENT_HANDLER;
  1360. assert(playerID > PlayerColor::PLAYER_LIMIT || status.getBattle() == UPCOMING_BATTLE);
  1361. status.setBattle(ONGOING_BATTLE);
  1362. 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
  1363. 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());
  1364. CAdventureAI::battleStart(army1, army2, tile, hero1, hero2, side);
  1365. }
  1366. void VCAI::battleEnd(const BattleResult * br, QueryID queryID)
  1367. {
  1368. NET_EVENT_HANDLER;
  1369. assert(status.getBattle() == ONGOING_BATTLE);
  1370. status.setBattle(ENDING_BATTLE);
  1371. bool won = br->winner == myCb->battleGetMySide();
  1372. logAi->debug("Player %d (%s): I %s the %s!", playerID, playerID.getStr(), (won ? "won" : "lost"), battlename);
  1373. battlename.clear();
  1374. status.addQuery(queryID, "Combat result dialog");
  1375. const int confirmAction = 0;
  1376. requestActionASAP([=]()
  1377. {
  1378. answerQuery(queryID, confirmAction);
  1379. });
  1380. CAdventureAI::battleEnd(br, queryID);
  1381. }
  1382. void VCAI::waitTillFree()
  1383. {
  1384. auto unlock = vstd::makeUnlockSharedGuard(CGameState::mutex);
  1385. status.waitTillFree();
  1386. }
  1387. void VCAI::markObjectVisited(const CGObjectInstance * obj)
  1388. {
  1389. if(!obj)
  1390. return;
  1391. if(const auto * rewardable = dynamic_cast<const CRewardableObject *>(obj)) //we may want to visit it with another hero
  1392. {
  1393. if (rewardable->configuration.getVisitMode() == Rewardable::VISIT_HERO) //we may want to visit it with another hero
  1394. return;
  1395. if (rewardable->configuration.getVisitMode() == Rewardable::VISIT_BONUS) //or another time
  1396. return;
  1397. }
  1398. if(obj->ID == Obj::MONSTER)
  1399. return;
  1400. alreadyVisited.insert(obj);
  1401. }
  1402. void VCAI::reserveObject(HeroPtr h, const CGObjectInstance * obj)
  1403. {
  1404. reservedObjs.insert(obj);
  1405. reservedHeroesMap[h].insert(obj);
  1406. logAi->debug("reserved object id=%d; address=%p; name=%s", obj->id, obj, obj->getObjectName());
  1407. }
  1408. void VCAI::unreserveObject(HeroPtr h, const CGObjectInstance * obj)
  1409. {
  1410. vstd::erase_if_present(reservedObjs, obj); //unreserve objects
  1411. vstd::erase_if_present(reservedHeroesMap[h], obj);
  1412. }
  1413. void VCAI::markHeroUnableToExplore(HeroPtr h)
  1414. {
  1415. heroesUnableToExplore.insert(h);
  1416. }
  1417. void VCAI::markHeroAbleToExplore(HeroPtr h)
  1418. {
  1419. vstd::erase_if_present(heroesUnableToExplore, h);
  1420. }
  1421. bool VCAI::isAbleToExplore(HeroPtr h)
  1422. {
  1423. return !vstd::contains(heroesUnableToExplore, h);
  1424. }
  1425. void VCAI::clearPathsInfo()
  1426. {
  1427. heroesUnableToExplore.clear();
  1428. }
  1429. void VCAI::validateVisitableObjs()
  1430. {
  1431. std::string errorMsg;
  1432. auto shouldBeErased = [&](const CGObjectInstance * obj) -> bool
  1433. {
  1434. if(obj)
  1435. return !cb->getObj(obj->id, false); // no verbose output needed as we check object visibility
  1436. else
  1437. return true;
  1438. };
  1439. //errorMsg is captured by ref so lambda will take the new text
  1440. errorMsg = " shouldn't be on the visitable objects list!";
  1441. vstd::erase_if(visitableObjs, shouldBeErased);
  1442. //FIXME: how comes our own heroes become inaccessible?
  1443. vstd::erase_if(reservedHeroesMap, [](std::pair<HeroPtr, std::set<const CGObjectInstance *>> hp) -> bool
  1444. {
  1445. return !hp.first.get(true);
  1446. });
  1447. for(auto & p : reservedHeroesMap)
  1448. {
  1449. errorMsg = " shouldn't be on list for hero " + p.first->getNameTranslated() + "!";
  1450. vstd::erase_if(p.second, shouldBeErased);
  1451. }
  1452. errorMsg = " shouldn't be on the reserved objs list!";
  1453. vstd::erase_if(reservedObjs, shouldBeErased);
  1454. //TODO overkill, hidden object should not be removed. However, we can't know if hidden object is erased from game.
  1455. errorMsg = " shouldn't be on the already visited objs list!";
  1456. vstd::erase_if(alreadyVisited, shouldBeErased);
  1457. }
  1458. void VCAI::retrieveVisitableObjs(std::vector<const CGObjectInstance *> & out, bool includeOwned) const
  1459. {
  1460. foreach_tile_pos([&](const int3 & pos)
  1461. {
  1462. for(const CGObjectInstance * obj : myCb->getVisitableObjs(pos, false))
  1463. {
  1464. if(includeOwned || obj->tempOwner != playerID)
  1465. out.push_back(obj);
  1466. }
  1467. });
  1468. }
  1469. void VCAI::retrieveVisitableObjs()
  1470. {
  1471. foreach_tile_pos([&](const int3 & pos)
  1472. {
  1473. for(const CGObjectInstance * obj : myCb->getVisitableObjs(pos, false))
  1474. {
  1475. if(obj->tempOwner != playerID)
  1476. addVisitableObj(obj);
  1477. }
  1478. });
  1479. }
  1480. std::vector<const CGObjectInstance *> VCAI::getFlaggedObjects() const
  1481. {
  1482. std::vector<const CGObjectInstance *> ret;
  1483. for(const CGObjectInstance * obj : visitableObjs)
  1484. {
  1485. if(obj->tempOwner == playerID)
  1486. ret.push_back(obj);
  1487. }
  1488. return ret;
  1489. }
  1490. void VCAI::addVisitableObj(const CGObjectInstance * obj)
  1491. {
  1492. if(obj->ID == Obj::EVENT)
  1493. return;
  1494. visitableObjs.insert(obj);
  1495. // All teleport objects seen automatically assigned to appropriate channels
  1496. auto teleportObj = dynamic_cast<const CGTeleport *>(obj);
  1497. if(teleportObj)
  1498. CGTeleport::addToChannel(knownTeleportChannels, teleportObj);
  1499. }
  1500. const CGObjectInstance * VCAI::lookForArt(int aid) const
  1501. {
  1502. for(const CGObjectInstance * obj : ai->visitableObjs)
  1503. {
  1504. if(obj->ID == Obj::ARTIFACT && obj->subID == aid)
  1505. return obj;
  1506. }
  1507. return nullptr;
  1508. //TODO what if more than one artifact is available? return them all or some slection criteria
  1509. }
  1510. bool VCAI::isAccessible(const int3 & pos) const
  1511. {
  1512. //TODO precalculate for speed
  1513. for(const CGHeroInstance * h : cb->getHeroesInfo())
  1514. {
  1515. if(isAccessibleForHero(pos, h))
  1516. return true;
  1517. }
  1518. return false;
  1519. }
  1520. HeroPtr VCAI::getHeroWithGrail() const
  1521. {
  1522. for(const CGHeroInstance * h : cb->getHeroesInfo())
  1523. {
  1524. if(h->hasArt(ArtifactID::GRAIL))
  1525. return h;
  1526. }
  1527. return nullptr;
  1528. }
  1529. const CGObjectInstance * VCAI::getUnvisitedObj(const std::function<bool(const CGObjectInstance *)> & predicate)
  1530. {
  1531. //TODO smarter definition of unvisited
  1532. for(const CGObjectInstance * obj : visitableObjs)
  1533. {
  1534. if(predicate(obj) && !vstd::contains(alreadyVisited, obj))
  1535. return obj;
  1536. }
  1537. return nullptr;
  1538. }
  1539. bool VCAI::isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies) const
  1540. {
  1541. // Don't visit tile occupied by allied hero
  1542. if(!includeAllies)
  1543. {
  1544. for(auto obj : cb->getVisitableObjs(pos))
  1545. {
  1546. if(obj->ID == Obj::HERO && cb->getPlayerRelations(ai->playerID, obj->tempOwner) != PlayerRelations::ENEMIES)
  1547. {
  1548. if(obj != h.get())
  1549. return false;
  1550. }
  1551. }
  1552. }
  1553. return cb->getPathsInfo(h.get())->getPathInfo(pos)->reachable();
  1554. }
  1555. bool VCAI::moveHeroToTile(int3 dst, HeroPtr h)
  1556. {
  1557. //TODO: consider if blockVisit objects change something in our checks: AIUtility::isBlockVisitObj()
  1558. auto afterMovementCheck = [&]() -> void
  1559. {
  1560. waitTillFree(); //movement may cause battle or blocking dialog
  1561. if(!h)
  1562. {
  1563. lostHero(h);
  1564. teleportChannelProbingList.clear();
  1565. if(status.channelProbing()) // if hero lost during channel probing we need to switch this mode off
  1566. status.setChannelProbing(false);
  1567. throw cannotFulfillGoalException("Hero was lost!");
  1568. }
  1569. };
  1570. logAi->debug("Moving hero %s to tile %s", h->getNameTranslated(), dst.toString());
  1571. int3 startHpos = h->visitablePos();
  1572. bool ret = false;
  1573. if(startHpos == dst)
  1574. {
  1575. //FIXME: this assertion fails also if AI moves onto defeated guarded object
  1576. assert(cb->getVisitableObjs(dst).size() > 1); //there's no point in revisiting tile where there is no visitable object
  1577. cb->moveHero(*h, h->convertFromVisitablePos(dst));
  1578. afterMovementCheck(); // TODO: is it feasible to hero get killed there if game work properly?
  1579. // If revisiting, teleport probing is never done, and so the entries into the list would remain unused and uncleared
  1580. teleportChannelProbingList.clear();
  1581. // not sure if AI can currently reconsider to attack bank while staying on it. Check issue 2084 on mantis for more information.
  1582. ret = true;
  1583. }
  1584. else
  1585. {
  1586. CGPath path;
  1587. cb->getPathsInfo(h.get())->getPath(path, dst);
  1588. if(path.nodes.empty())
  1589. {
  1590. logAi->error("Hero %s cannot reach %s.", h->getNameTranslated(), dst.toString());
  1591. throw goalFulfilledException(sptr(Goals::VisitTile(dst).sethero(h)));
  1592. }
  1593. int i = (int)path.nodes.size() - 1;
  1594. auto getObj = [&](int3 coord, bool ignoreHero)
  1595. {
  1596. auto tile = cb->getTile(coord, false);
  1597. assert(tile);
  1598. return tile->topVisitableObj(ignoreHero);
  1599. //return cb->getTile(coord,false)->topVisitableObj(ignoreHero);
  1600. };
  1601. auto isTeleportAction = [&](EPathNodeAction action) -> bool
  1602. {
  1603. if(action != EPathNodeAction::TELEPORT_NORMAL && action != EPathNodeAction::TELEPORT_BLOCKING_VISIT)
  1604. {
  1605. if(action != EPathNodeAction::TELEPORT_BATTLE)
  1606. {
  1607. return false;
  1608. }
  1609. }
  1610. return true;
  1611. };
  1612. auto getDestTeleportObj = [&](const CGObjectInstance * currentObject, const CGObjectInstance * nextObjectTop, const CGObjectInstance * nextObject) -> const CGObjectInstance *
  1613. {
  1614. if(CGTeleport::isConnected(currentObject, nextObjectTop))
  1615. return nextObjectTop;
  1616. if(nextObjectTop && nextObjectTop->ID == Obj::HERO)
  1617. {
  1618. if(CGTeleport::isConnected(currentObject, nextObject))
  1619. return nextObject;
  1620. }
  1621. return nullptr;
  1622. };
  1623. auto doMovement = [&](int3 dst, bool transit)
  1624. {
  1625. cb->moveHero(*h, h->convertFromVisitablePos(dst), transit);
  1626. };
  1627. auto doTeleportMovement = [&](ObjectInstanceID exitId, int3 exitPos)
  1628. {
  1629. destinationTeleport = exitId;
  1630. if(exitPos.valid())
  1631. destinationTeleportPos = h->convertFromVisitablePos(exitPos);
  1632. cb->moveHero(*h, h->pos);
  1633. destinationTeleport = ObjectInstanceID();
  1634. destinationTeleportPos = int3(-1);
  1635. afterMovementCheck();
  1636. };
  1637. auto doChannelProbing = [&]() -> void
  1638. {
  1639. auto currentPos = h->visitablePos();
  1640. auto currentExit = getObj(currentPos, true)->id;
  1641. status.setChannelProbing(true);
  1642. for(auto exit : teleportChannelProbingList)
  1643. doTeleportMovement(exit, int3(-1));
  1644. teleportChannelProbingList.clear();
  1645. status.setChannelProbing(false);
  1646. doTeleportMovement(currentExit, currentPos);
  1647. };
  1648. for(; i > 0; i--)
  1649. {
  1650. int3 currentCoord = path.nodes[i].coord;
  1651. int3 nextCoord = path.nodes[i - 1].coord;
  1652. auto currentObject = getObj(currentCoord, currentCoord == h->visitablePos());
  1653. auto nextObjectTop = getObj(nextCoord, false);
  1654. auto nextObject = getObj(nextCoord, true);
  1655. auto destTeleportObj = getDestTeleportObj(currentObject, nextObjectTop, nextObject);
  1656. if(isTeleportAction(path.nodes[i - 1].action) && destTeleportObj != nullptr)
  1657. {
  1658. //we use special login if hero standing on teleporter it's mean we need
  1659. doTeleportMovement(destTeleportObj->id, nextCoord);
  1660. if(teleportChannelProbingList.size())
  1661. doChannelProbing();
  1662. markObjectVisited(destTeleportObj); //FIXME: Monoliths are not correctly visited
  1663. continue;
  1664. }
  1665. //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  1666. if(path.nodes[i - 1].turns)
  1667. {
  1668. //blockedHeroes.insert(h); //to avoid attempts of moving heroes with very little MPs
  1669. break;
  1670. }
  1671. int3 endpos = path.nodes[i - 1].coord;
  1672. if(endpos == h->visitablePos())
  1673. continue;
  1674. bool isConnected = false;
  1675. bool isNextObjectTeleport = false;
  1676. // Check there is node after next one; otherwise transit is pointless
  1677. if(i - 2 >= 0)
  1678. {
  1679. isConnected = CGTeleport::isConnected(nextObjectTop, getObj(path.nodes[i - 2].coord, false));
  1680. isNextObjectTeleport = CGTeleport::isTeleport(nextObjectTop);
  1681. }
  1682. if(isConnected || isNextObjectTeleport)
  1683. {
  1684. // Hero should be able to go through object if it's allow transit
  1685. doMovement(endpos, true);
  1686. }
  1687. else if(path.nodes[i - 1].layer == EPathfindingLayer::AIR)
  1688. {
  1689. doMovement(endpos, true);
  1690. }
  1691. else
  1692. {
  1693. doMovement(endpos, false);
  1694. }
  1695. afterMovementCheck();
  1696. if(teleportChannelProbingList.size())
  1697. doChannelProbing();
  1698. }
  1699. if(path.nodes[0].action == EPathNodeAction::BLOCKING_VISIT)
  1700. {
  1701. ret = h && i == 0; // when we take resource we do not reach its position. We even might not move
  1702. }
  1703. }
  1704. if(h)
  1705. {
  1706. if(auto visitedObject = vstd::frontOrNull(cb->getVisitableObjs(h->visitablePos()))) //we stand on something interesting
  1707. {
  1708. if(visitedObject != *h)
  1709. performObjectInteraction(visitedObject, h);
  1710. }
  1711. }
  1712. if(h) //we could have lost hero after last move
  1713. {
  1714. completeGoal(sptr(Goals::VisitTile(dst).sethero(h))); //we stepped on some tile, anyway
  1715. completeGoal(sptr(Goals::ClearWayTo(dst).sethero(h)));
  1716. ret = ret || (dst == h->visitablePos());
  1717. if(!ret) //reserve object we are heading towards
  1718. {
  1719. auto obj = vstd::frontOrNull(cb->getVisitableObjs(dst));
  1720. if(obj && obj != *h)
  1721. reserveObject(h, obj);
  1722. }
  1723. if(startHpos == h->visitablePos() && !ret) //we didn't move and didn't reach the target
  1724. {
  1725. vstd::erase_if_present(lockedHeroes, h); //hero seemingly is confused or has only 95mp which is not enough to move
  1726. invalidPathHeroes.insert(h);
  1727. throw cannotFulfillGoalException("Invalid path found!");
  1728. }
  1729. evaluateGoal(h); //new hero position means new game situation
  1730. logAi->debug("Hero %s moved from %s to %s. Returning %d.", h->getNameTranslated(), startHpos.toString(), h->visitablePos().toString(), ret);
  1731. }
  1732. return ret;
  1733. }
  1734. void VCAI::buildStructure(const CGTownInstance * t, BuildingID building)
  1735. {
  1736. auto name = t->town->buildings.at(building)->getNameTranslated();
  1737. logAi->debug("Player %d will build %s in town of %s at %s", ai->playerID, name, t->getNameTranslated(), t->pos.toString());
  1738. cb->buildBuilding(t, building); //just do this;
  1739. }
  1740. void VCAI::tryRealize(Goals::Explore & g)
  1741. {
  1742. throw cannotFulfillGoalException("EXPLORE is not an elementar goal!");
  1743. }
  1744. void VCAI::tryRealize(Goals::RecruitHero & g)
  1745. {
  1746. if(const CGTownInstance * t = findTownWithTavern())
  1747. {
  1748. recruitHero(t, true);
  1749. //TODO try to free way to blocked town
  1750. //TODO: adventure map tavern or prison?
  1751. }
  1752. else
  1753. {
  1754. throw cannotFulfillGoalException("No town to recruit hero!");
  1755. }
  1756. }
  1757. void VCAI::tryRealize(Goals::VisitTile & g)
  1758. {
  1759. if(!g.hero->movement)
  1760. throw cannotFulfillGoalException("Cannot visit tile: hero is out of MPs!");
  1761. if(g.tile == g.hero->visitablePos() && cb->getVisitableObjs(g.hero->visitablePos()).size() < 2)
  1762. {
  1763. logAi->warn("Why do I want to move hero %s to tile %s? Already standing on that tile! ", g.hero->getNameTranslated(), g.tile.toString());
  1764. throw goalFulfilledException(sptr(g));
  1765. }
  1766. if(ai->moveHeroToTile(g.tile, g.hero.get()))
  1767. {
  1768. throw goalFulfilledException(sptr(g));
  1769. }
  1770. }
  1771. void VCAI::tryRealize(Goals::VisitObj & g)
  1772. {
  1773. auto position = g.tile;
  1774. if(!g.hero->movement)
  1775. throw cannotFulfillGoalException("Cannot visit object: hero is out of MPs!");
  1776. if(position == g.hero->visitablePos() && cb->getVisitableObjs(g.hero->visitablePos()).size() < 2)
  1777. {
  1778. logAi->warn("Why do I want to move hero %s to tile %s? Already standing on that tile! ", g.hero->getNameTranslated(), g.tile.toString());
  1779. throw goalFulfilledException(sptr(g));
  1780. }
  1781. if(ai->moveHeroToTile(position, g.hero.get()))
  1782. {
  1783. throw goalFulfilledException(sptr(g));
  1784. }
  1785. }
  1786. void VCAI::tryRealize(Goals::VisitHero & g)
  1787. {
  1788. if(!g.hero->movement)
  1789. throw cannotFulfillGoalException("Cannot visit target hero: hero is out of MPs!");
  1790. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(g.objid));
  1791. if(obj)
  1792. {
  1793. if(ai->moveHeroToTile(obj->visitablePos(), g.hero.get()))
  1794. {
  1795. throw goalFulfilledException(sptr(g));
  1796. }
  1797. }
  1798. else
  1799. {
  1800. throw cannotFulfillGoalException("Cannot visit hero: object not found!");
  1801. }
  1802. }
  1803. void VCAI::tryRealize(Goals::BuildThis & g)
  1804. {
  1805. auto b = BuildingID(g.bid);
  1806. auto t = g.town;
  1807. if (t)
  1808. {
  1809. if (cb->canBuildStructure(t, b) == EBuildingState::ALLOWED)
  1810. {
  1811. logAi->debug("Player %d will build %s in town of %s at %s",
  1812. playerID, t->town->buildings.at(b)->getNameTranslated(), t->getNameTranslated(), t->pos.toString());
  1813. cb->buildBuilding(t, b);
  1814. throw goalFulfilledException(sptr(g));
  1815. }
  1816. }
  1817. throw cannotFulfillGoalException("Cannot build a given structure!");
  1818. }
  1819. void VCAI::tryRealize(Goals::DigAtTile & g)
  1820. {
  1821. assert(g.hero->visitablePos() == g.tile); //surely we want to crash here?
  1822. if(g.hero->diggingStatus() == EDiggingStatus::CAN_DIG)
  1823. {
  1824. cb->dig(g.hero.get());
  1825. completeGoal(sptr(g)); // finished digging
  1826. }
  1827. else
  1828. {
  1829. ai->lockedHeroes[g.hero] = sptr(g); //hero who tries to dig shouldn't do anything else
  1830. throw cannotFulfillGoalException("A hero can't dig!\n");
  1831. }
  1832. }
  1833. void VCAI::tryRealize(Goals::Trade & g) //trade
  1834. {
  1835. if(ah->freeResources()[g.resID] >= g.value) //goal is already fulfilled. Why we need this check, anyway?
  1836. throw goalFulfilledException(sptr(g));
  1837. int accquiredResources = 0;
  1838. if(const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(g.objid), false))
  1839. {
  1840. if(const IMarket * m = IMarket::castFrom(obj, false))
  1841. {
  1842. auto freeRes = ah->freeResources(); //trade only resources which are not reserved
  1843. for(auto it = ResourceSet::nziterator(freeRes); it.valid(); it++)
  1844. {
  1845. auto res = it->resType;
  1846. if(res.getNum() == g.resID) //sell any other resource
  1847. continue;
  1848. int toGive, toGet;
  1849. m->getOffer(res, g.resID, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  1850. toGive = static_cast<int>(toGive * (it->resVal / toGive)); //round down
  1851. //TODO trade only as much as needed
  1852. if (toGive) //don't try to sell 0 resources
  1853. {
  1854. cb->trade(m, EMarketMode::RESOURCE_RESOURCE, res, g.resID, toGive);
  1855. accquiredResources = static_cast<int>(toGet * (it->resVal / toGive));
  1856. logAi->debug("Traded %d of %s for %d of %s at %s", toGive, res, accquiredResources, g.resID, obj->getObjectName());
  1857. }
  1858. if (ah->freeResources()[g.resID] >= g.value)
  1859. throw goalFulfilledException(sptr(g)); //we traded all we needed
  1860. }
  1861. throw cannotFulfillGoalException("I cannot get needed resources by trade!");
  1862. }
  1863. else
  1864. {
  1865. throw cannotFulfillGoalException("I don't know how to use this object to raise resources!");
  1866. }
  1867. }
  1868. else
  1869. {
  1870. throw cannotFulfillGoalException("No object that could be used to raise resources!");
  1871. }
  1872. }
  1873. void VCAI::tryRealize(Goals::BuyArmy & g)
  1874. {
  1875. auto t = g.town;
  1876. ui64 valueBought = 0;
  1877. //buy the stacks with largest AI value
  1878. makePossibleUpgrades(t);
  1879. while (valueBought < g.value)
  1880. {
  1881. auto res = ah->allResources();
  1882. std::vector<creInfo> creaturesInDwellings;
  1883. for (int i = 0; i < t->creatures.size(); i++)
  1884. {
  1885. auto ci = infoFromDC(t->creatures[i]);
  1886. if(!ci.count
  1887. || ci.creID == -1
  1888. || (g.objid != -1 && ci.creID != g.objid)
  1889. || t->getUpperArmy()->getSlotFor(ci.creID) == SlotID())
  1890. continue;
  1891. vstd::amin(ci.count, res / ci.cre->getFullRecruitCost()); //max count we can afford
  1892. if(!ci.count)
  1893. continue;
  1894. ci.level = i; //this is important for Dungeon Summoning Portal
  1895. creaturesInDwellings.push_back(ci);
  1896. }
  1897. if (creaturesInDwellings.empty())
  1898. throw cannotFulfillGoalException("Can't buy any more creatures!");
  1899. creInfo ci =
  1900. *boost::max_element(creaturesInDwellings, [](const creInfo & lhs, const creInfo & rhs)
  1901. {
  1902. //max value of creatures we can buy with our res
  1903. int value1 = lhs.cre->getAIValue() * lhs.count,
  1904. value2 = rhs.cre->getAIValue() * rhs.count;
  1905. return value1 < value2;
  1906. });
  1907. cb->recruitCreatures(t, t->getUpperArmy(), ci.creID, ci.count, ci.level);
  1908. valueBought += ci.count * ci.cre->getAIValue();
  1909. }
  1910. throw goalFulfilledException(sptr(g)); //we bought as many creatures as we wanted
  1911. }
  1912. void VCAI::tryRealize(Goals::Invalid & g)
  1913. {
  1914. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1915. }
  1916. void VCAI::tryRealize(Goals::AbstractGoal & g)
  1917. {
  1918. logAi->debug("Attempting realizing goal with code %s", g.name());
  1919. throw cannotFulfillGoalException("Unknown type of goal !");
  1920. }
  1921. const CGTownInstance * VCAI::findTownWithTavern() const
  1922. {
  1923. for(const CGTownInstance * t : cb->getTownsInfo())
  1924. if(t->hasBuilt(BuildingID::TAVERN) && !t->visitingHero)
  1925. return t;
  1926. return nullptr;
  1927. }
  1928. Goals::TSubgoal VCAI::getGoal(HeroPtr h) const
  1929. {
  1930. auto it = lockedHeroes.find(h);
  1931. if(it != lockedHeroes.end())
  1932. return it->second;
  1933. else
  1934. return sptr(Goals::Invalid());
  1935. }
  1936. std::vector<HeroPtr> VCAI::getUnblockedHeroes() const
  1937. {
  1938. std::vector<HeroPtr> ret;
  1939. for(auto h : cb->getHeroesInfo())
  1940. {
  1941. //&& !vstd::contains(lockedHeroes, h)
  1942. //at this point we assume heroes exhausted their locked goals
  1943. if(canAct(h))
  1944. ret.push_back(h);
  1945. }
  1946. return ret;
  1947. }
  1948. bool VCAI::canAct(HeroPtr h) const
  1949. {
  1950. auto mission = lockedHeroes.find(h);
  1951. if(mission != lockedHeroes.end())
  1952. {
  1953. //FIXME: I'm afraid there can be other conditions when heroes can act but not move :?
  1954. if(mission->second->goalType == Goals::DIG_AT_TILE && !mission->second->isElementar)
  1955. return false;
  1956. }
  1957. return h->movement;
  1958. }
  1959. HeroPtr VCAI::primaryHero() const
  1960. {
  1961. auto hs = cb->getHeroesInfo();
  1962. if (hs.empty())
  1963. return nullptr;
  1964. else
  1965. return *boost::max_element(hs, compareHeroStrength);
  1966. }
  1967. void VCAI::endTurn()
  1968. {
  1969. logAi->info("Player %d (%s) ends turn", playerID, playerID.getStr());
  1970. if(!status.haveTurn())
  1971. {
  1972. logAi->error("Not having turn at the end of turn???");
  1973. }
  1974. logAi->debug("Resources at the end of turn: %s", cb->getResourceAmount().toString());
  1975. do
  1976. {
  1977. cb->endTurn();
  1978. }
  1979. 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
  1980. logGlobal->info("Player %d (%s) ended turn", playerID, playerID.getStr());
  1981. }
  1982. void VCAI::striveToGoal(Goals::TSubgoal basicGoal)
  1983. {
  1984. //TODO: this function is deprecated and should be dropped altogether
  1985. auto goalToDecompose = basicGoal;
  1986. Goals::TSubgoal elementarGoal = sptr(Goals::Invalid());
  1987. int maxAbstractGoals = 10;
  1988. while (!elementarGoal->isElementar && maxAbstractGoals)
  1989. {
  1990. try
  1991. {
  1992. elementarGoal = decomposeGoal(goalToDecompose);
  1993. }
  1994. catch (goalFulfilledException & e)
  1995. {
  1996. //it is impossible to continue some goals (like exploration, for example)
  1997. completeGoal(e.goal); //put in goalsToRemove
  1998. logAi->debug("Goal %s decomposition failed: goal was completed as much as possible", e.goal->name());
  1999. return;
  2000. }
  2001. catch (std::exception & e)
  2002. {
  2003. goalsToRemove.push_back(basicGoal);
  2004. logAi->debug("Goal %s decomposition failed: %s", basicGoal->name(), e.what());
  2005. return;
  2006. }
  2007. if (elementarGoal->isAbstract) //we can decompose it further
  2008. {
  2009. goalsToAdd.push_back(elementarGoal);
  2010. //decompose further now - this is necesssary if we can't add over 10 goals in the pool
  2011. goalToDecompose = elementarGoal;
  2012. //there is a risk of infinite abstract goal loop, though it indicates failed logic
  2013. maxAbstractGoals--;
  2014. }
  2015. else if (elementarGoal->isElementar) //should be
  2016. {
  2017. logAi->debug("Found elementar goal %s", elementarGoal->name());
  2018. ultimateGoalsFromBasic[elementarGoal].push_back(goalToDecompose); //TODO: how about indirect basicGoal?
  2019. break;
  2020. }
  2021. else //should never be here
  2022. throw cannotFulfillGoalException("Goal %s is neither abstract nor elementar!" + basicGoal->name());
  2023. }
  2024. //realize best goal
  2025. if (!elementarGoal->invalid())
  2026. {
  2027. logAi->debug("Trying to realize %s (value %2.3f)", elementarGoal->name(), elementarGoal->priority);
  2028. try
  2029. {
  2030. boost::this_thread::interruption_point();
  2031. elementarGoal->accept(this); //visitor pattern
  2032. boost::this_thread::interruption_point();
  2033. }
  2034. catch (boost::thread_interrupted & e)
  2035. {
  2036. (void)e;
  2037. logAi->debug("Player %d: Making turn thread received an interruption!", playerID);
  2038. throw; //rethrow, we want to truly end this thread
  2039. }
  2040. catch (goalFulfilledException & e)
  2041. {
  2042. //the sub-goal was completed successfully
  2043. completeGoal(e.goal);
  2044. //local goal was also completed
  2045. completeGoal(elementarGoal);
  2046. }
  2047. catch (std::exception & e)
  2048. {
  2049. logAi->debug("Failed to realize subgoal of type %s, I will stop.", elementarGoal->name());
  2050. logAi->debug("The error message was: %s", e.what());
  2051. //erase base goal if we failed to execute decomposed goal
  2052. for (auto basicGoalToRemove : ultimateGoalsFromBasic[elementarGoal])
  2053. goalsToRemove.push_back(basicGoalToRemove);
  2054. }
  2055. }
  2056. }
  2057. Goals::TSubgoal VCAI::decomposeGoal(Goals::TSubgoal ultimateGoal)
  2058. {
  2059. if(ultimateGoal->isElementar)
  2060. {
  2061. logAi->warn("Trying to decompose elementar goal %s", ultimateGoal->name());
  2062. return ultimateGoal;
  2063. }
  2064. const int searchDepth = 30;
  2065. Goals::TSubgoal goal = ultimateGoal;
  2066. logAi->debug("Decomposing goal %s", ultimateGoal->name());
  2067. int maxGoals = searchDepth; //preventing deadlock for mutually dependent goals
  2068. while (maxGoals)
  2069. {
  2070. boost::this_thread::interruption_point();
  2071. goal = goal->whatToDoToAchieve(); //may throw if decomposition fails
  2072. --maxGoals;
  2073. if (goal == ultimateGoal) //compare objects by value
  2074. if (goal->isElementar == ultimateGoal->isElementar)
  2075. throw cannotFulfillGoalException((boost::format("Goal dependency loop detected for %s!")
  2076. % ultimateGoal->name()).str());
  2077. if (goal->isAbstract || goal->isElementar)
  2078. return goal;
  2079. else
  2080. logAi->debug("Considering: %s", goal->name());
  2081. }
  2082. throw cannotFulfillGoalException("Too many subgoals, don't know what to do");
  2083. }
  2084. void VCAI::performTypicalActions()
  2085. {
  2086. for(auto h : getUnblockedHeroes())
  2087. {
  2088. if(!h) //hero might be lost. getUnblockedHeroes() called once on start of turn
  2089. continue;
  2090. logAi->debug("Hero %s started wandering, MP=%d", h->getNameTranslated(), h->movement);
  2091. makePossibleUpgrades(*h);
  2092. pickBestArtifacts(*h);
  2093. try
  2094. {
  2095. wander(h);
  2096. }
  2097. catch(std::exception & e)
  2098. {
  2099. logAi->debug("Cannot use this hero anymore, received exception: %s", e.what());
  2100. continue;
  2101. }
  2102. }
  2103. }
  2104. void VCAI::buildArmyIn(const CGTownInstance * t)
  2105. {
  2106. makePossibleUpgrades(t->visitingHero);
  2107. makePossibleUpgrades(t);
  2108. recruitCreatures(t, t->getUpperArmy());
  2109. moveCreaturesToHero(t);
  2110. }
  2111. void VCAI::checkHeroArmy(HeroPtr h)
  2112. {
  2113. auto it = lockedHeroes.find(h);
  2114. if(it != lockedHeroes.end())
  2115. {
  2116. if(it->second->goalType == Goals::GATHER_ARMY && it->second->value <= h->getArmyStrength())
  2117. completeGoal(sptr(Goals::GatherArmy(it->second->value).sethero(h)));
  2118. }
  2119. }
  2120. void VCAI::recruitHero(const CGTownInstance * t, bool throwing)
  2121. {
  2122. logAi->debug("Trying to recruit a hero in %s at %s", t->getNameTranslated(), t->visitablePos().toString());
  2123. auto heroes = cb->getAvailableHeroes(t);
  2124. if(heroes.size())
  2125. {
  2126. auto hero = heroes[0];
  2127. if(heroes.size() >= 2) //makes sense to recruit two heroes with starting amries in first week
  2128. {
  2129. if(heroes[1]->getTotalStrength() > hero->getTotalStrength())
  2130. hero = heroes[1];
  2131. }
  2132. cb->recruitHero(t, hero);
  2133. throw goalFulfilledException(sptr(Goals::RecruitHero().settown(t)));
  2134. }
  2135. else if(throwing)
  2136. {
  2137. throw cannotFulfillGoalException("No available heroes in tavern in " + t->nodeName());
  2138. }
  2139. }
  2140. void VCAI::finish()
  2141. {
  2142. //we want to lock to avoid multiple threads from calling makingTurn->join() at same time
  2143. boost::lock_guard<boost::mutex> multipleCleanupGuard(turnInterruptionMutex);
  2144. if(makingTurn)
  2145. {
  2146. makingTurn->interrupt();
  2147. makingTurn->join();
  2148. makingTurn.reset();
  2149. }
  2150. }
  2151. void VCAI::requestActionASAP(std::function<void()> whatToDo)
  2152. {
  2153. boost::thread newThread([this, whatToDo]()
  2154. {
  2155. setThreadName("VCAI::requestActionASAP::whatToDo");
  2156. SET_GLOBAL_STATE(this);
  2157. boost::shared_lock<boost::shared_mutex> gsLock(CGameState::mutex);
  2158. whatToDo();
  2159. });
  2160. }
  2161. void VCAI::lostHero(HeroPtr h)
  2162. {
  2163. logAi->debug("I lost my hero %s. It's best to forget and move on.", h.name);
  2164. vstd::erase_if_present(lockedHeroes, h);
  2165. for(auto obj : reservedHeroesMap[h])
  2166. {
  2167. vstd::erase_if_present(reservedObjs, obj); //unreserve all objects for that hero
  2168. }
  2169. vstd::erase_if_present(reservedHeroesMap, h);
  2170. vstd::erase_if_present(visitedHeroes, h);
  2171. for (auto heroVec : visitedHeroes)
  2172. {
  2173. vstd::erase_if_present(heroVec.second, h);
  2174. }
  2175. //remove goals with removed hero assigned from main loop
  2176. vstd::erase_if(ultimateGoalsFromBasic, [&](const std::pair<Goals::TSubgoal, Goals::TGoalVec> & x) -> bool
  2177. {
  2178. if(x.first->hero == h)
  2179. return true;
  2180. else
  2181. return false;
  2182. });
  2183. auto removedHeroGoalPredicate = [&](const Goals::TSubgoal & x) ->bool
  2184. {
  2185. if(x->hero == h)
  2186. return true;
  2187. else
  2188. return false;
  2189. };
  2190. vstd::erase_if(basicGoals, removedHeroGoalPredicate);
  2191. vstd::erase_if(goalsToAdd, removedHeroGoalPredicate);
  2192. vstd::erase_if(goalsToRemove, removedHeroGoalPredicate);
  2193. for(auto goal : ultimateGoalsFromBasic)
  2194. vstd::erase_if(goal.second, removedHeroGoalPredicate);
  2195. }
  2196. void VCAI::answerQuery(QueryID queryID, int selection)
  2197. {
  2198. logAi->debug("I'll answer the query %d giving the choice %d", queryID, selection);
  2199. if(queryID != QueryID(-1))
  2200. {
  2201. cb->selectionMade(selection, queryID);
  2202. }
  2203. else
  2204. {
  2205. logAi->debug("Since the query ID is %d, the answer won't be sent. This is not a real query!", queryID);
  2206. //do nothing
  2207. }
  2208. }
  2209. void VCAI::requestSent(const CPackForServer * pack, int requestID)
  2210. {
  2211. //BNLOG("I have sent request of type %s", typeid(*pack).name());
  2212. if(auto reply = dynamic_cast<const QueryReply *>(pack))
  2213. {
  2214. status.attemptedAnsweringQuery(reply->qid, requestID);
  2215. }
  2216. }
  2217. std::string VCAI::getBattleAIName() const
  2218. {
  2219. if(settings["server"]["enemyAI"].getType() == JsonNode::JsonType::DATA_STRING)
  2220. return settings["server"]["enemyAI"].String();
  2221. else
  2222. return "BattleAI";
  2223. }
  2224. void VCAI::validateObject(const CGObjectInstance * obj)
  2225. {
  2226. validateObject(obj->id);
  2227. }
  2228. void VCAI::validateObject(ObjectIdRef obj)
  2229. {
  2230. auto matchesId = [&](const CGObjectInstance * hlpObj) -> bool
  2231. {
  2232. return hlpObj->id == obj.id;
  2233. };
  2234. if(!obj)
  2235. {
  2236. vstd::erase_if(visitableObjs, matchesId);
  2237. for(auto & p : reservedHeroesMap)
  2238. vstd::erase_if(p.second, matchesId);
  2239. vstd::erase_if(reservedObjs, matchesId);
  2240. }
  2241. }
  2242. AIStatus::AIStatus()
  2243. {
  2244. battle = NO_BATTLE;
  2245. havingTurn = false;
  2246. ongoingHeroMovement = false;
  2247. ongoingChannelProbing = false;
  2248. }
  2249. AIStatus::~AIStatus()
  2250. {
  2251. }
  2252. void AIStatus::setBattle(BattleState BS)
  2253. {
  2254. boost::unique_lock<boost::mutex> lock(mx);
  2255. LOG_TRACE_PARAMS(logAi, "battle state=%d", (int)BS);
  2256. battle = BS;
  2257. cv.notify_all();
  2258. }
  2259. BattleState AIStatus::getBattle()
  2260. {
  2261. boost::unique_lock<boost::mutex> lock(mx);
  2262. return battle;
  2263. }
  2264. void AIStatus::addQuery(QueryID ID, std::string description)
  2265. {
  2266. if(ID == QueryID(-1))
  2267. {
  2268. logAi->debug("The \"query\" has an id %d, it'll be ignored as non-query. Description: %s", ID, description);
  2269. return;
  2270. }
  2271. assert(ID.getNum() >= 0);
  2272. boost::unique_lock<boost::mutex> lock(mx);
  2273. assert(!vstd::contains(remainingQueries, ID));
  2274. remainingQueries[ID] = description;
  2275. cv.notify_all();
  2276. logAi->debug("Adding query %d - %s. Total queries count: %d", ID, description, remainingQueries.size());
  2277. }
  2278. void AIStatus::removeQuery(QueryID ID)
  2279. {
  2280. boost::unique_lock<boost::mutex> lock(mx);
  2281. assert(vstd::contains(remainingQueries, ID));
  2282. std::string description = remainingQueries[ID];
  2283. remainingQueries.erase(ID);
  2284. cv.notify_all();
  2285. logAi->debug("Removing query %d - %s. Total queries count: %d", ID, description, remainingQueries.size());
  2286. }
  2287. int AIStatus::getQueriesCount()
  2288. {
  2289. boost::unique_lock<boost::mutex> lock(mx);
  2290. return static_cast<int>(remainingQueries.size());
  2291. }
  2292. void AIStatus::startedTurn()
  2293. {
  2294. boost::unique_lock<boost::mutex> lock(mx);
  2295. havingTurn = true;
  2296. cv.notify_all();
  2297. }
  2298. void AIStatus::madeTurn()
  2299. {
  2300. boost::unique_lock<boost::mutex> lock(mx);
  2301. havingTurn = false;
  2302. cv.notify_all();
  2303. }
  2304. void AIStatus::waitTillFree()
  2305. {
  2306. boost::unique_lock<boost::mutex> lock(mx);
  2307. while(battle != NO_BATTLE || !remainingQueries.empty() || !objectsBeingVisited.empty() || ongoingHeroMovement)
  2308. cv.timed_wait(lock, boost::posix_time::milliseconds(100));
  2309. }
  2310. bool AIStatus::haveTurn()
  2311. {
  2312. boost::unique_lock<boost::mutex> lock(mx);
  2313. return havingTurn;
  2314. }
  2315. void AIStatus::attemptedAnsweringQuery(QueryID queryID, int answerRequestID)
  2316. {
  2317. boost::unique_lock<boost::mutex> lock(mx);
  2318. assert(vstd::contains(remainingQueries, queryID));
  2319. std::string description = remainingQueries[queryID];
  2320. logAi->debug("Attempted answering query %d - %s. Request id=%d. Waiting for results...", queryID, description, answerRequestID);
  2321. requestToQueryID[answerRequestID] = queryID;
  2322. }
  2323. void AIStatus::receivedAnswerConfirmation(int answerRequestID, int result)
  2324. {
  2325. QueryID query;
  2326. {
  2327. boost::unique_lock<boost::mutex> lock(mx);
  2328. assert(vstd::contains(requestToQueryID, answerRequestID));
  2329. query = requestToQueryID[answerRequestID];
  2330. assert(vstd::contains(remainingQueries, query));
  2331. requestToQueryID.erase(answerRequestID);
  2332. }
  2333. if(result)
  2334. {
  2335. removeQuery(query);
  2336. }
  2337. else
  2338. {
  2339. logAi->error("Something went really wrong, failed to answer query %d : %s", query.getNum(), remainingQueries[query]);
  2340. //TODO safely retry
  2341. }
  2342. }
  2343. void AIStatus::heroVisit(const CGObjectInstance * obj, bool started)
  2344. {
  2345. boost::unique_lock<boost::mutex> lock(mx);
  2346. if(started)
  2347. {
  2348. objectsBeingVisited.push_back(obj);
  2349. }
  2350. else
  2351. {
  2352. // There can be more than one object visited at the time (eg. hero visits Subterranean Gate
  2353. // causing visit to hero on the other side.
  2354. // However, we are guaranteed that start/end visit notification maintain stack order.
  2355. assert(!objectsBeingVisited.empty());
  2356. objectsBeingVisited.pop_back();
  2357. }
  2358. cv.notify_all();
  2359. }
  2360. void AIStatus::setMove(bool ongoing)
  2361. {
  2362. boost::unique_lock<boost::mutex> lock(mx);
  2363. ongoingHeroMovement = ongoing;
  2364. cv.notify_all();
  2365. }
  2366. void AIStatus::setChannelProbing(bool ongoing)
  2367. {
  2368. boost::unique_lock<boost::mutex> lock(mx);
  2369. ongoingChannelProbing = ongoing;
  2370. cv.notify_all();
  2371. }
  2372. bool AIStatus::channelProbing()
  2373. {
  2374. return ongoingChannelProbing;
  2375. }
  2376. bool isWeeklyRevisitable(const CGObjectInstance * obj)
  2377. {
  2378. //TODO: allow polling of remaining creatures in dwelling
  2379. if(const auto * rewardable = dynamic_cast<const CRewardableObject *>(obj))
  2380. return rewardable->configuration.getResetDuration() == 7;
  2381. if(dynamic_cast<const CGDwelling *>(obj))
  2382. return true;
  2383. if(dynamic_cast<const CBank *>(obj)) //banks tend to respawn often in mods
  2384. return true;
  2385. switch(obj->ID)
  2386. {
  2387. case Obj::STABLES:
  2388. case Obj::MAGIC_WELL:
  2389. case Obj::HILL_FORT:
  2390. return true;
  2391. case Obj::BORDER_GATE:
  2392. case Obj::BORDERGUARD:
  2393. return (dynamic_cast<const CGKeys *>(obj))->wasMyColorVisited(ai->playerID); //FIXME: they could be revisited sooner than in a week
  2394. }
  2395. return false;
  2396. }
  2397. bool shouldVisit(HeroPtr h, const CGObjectInstance * obj)
  2398. {
  2399. switch(obj->ID)
  2400. {
  2401. case Obj::TOWN:
  2402. case Obj::HERO: //never visit our heroes at random
  2403. return obj->tempOwner != h->tempOwner; //do not visit our towns at random
  2404. case Obj::BORDER_GATE:
  2405. {
  2406. for(auto q : ai->myCb->getMyQuests())
  2407. {
  2408. if(q.obj == obj)
  2409. {
  2410. return false; // do not visit guards or gates when wandering
  2411. }
  2412. }
  2413. return true; //we don't have this quest yet
  2414. }
  2415. case Obj::BORDERGUARD: //open borderguard if possible
  2416. return (dynamic_cast<const CGKeys *>(obj))->wasMyColorVisited(ai->playerID);
  2417. case Obj::SEER_HUT:
  2418. case Obj::QUEST_GUARD:
  2419. {
  2420. for(auto q : ai->myCb->getMyQuests())
  2421. {
  2422. if(q.obj == obj)
  2423. {
  2424. if(q.quest->checkQuest(h.h))
  2425. return true; //we completed the quest
  2426. else
  2427. return false; //we can't complete this quest
  2428. }
  2429. }
  2430. return true; //we don't have this quest yet
  2431. }
  2432. case Obj::CREATURE_GENERATOR1:
  2433. {
  2434. if(obj->tempOwner != h->tempOwner)
  2435. return true; //flag just in case
  2436. bool canRecruitCreatures = false;
  2437. const CGDwelling * d = dynamic_cast<const CGDwelling *>(obj);
  2438. for(auto level : d->creatures)
  2439. {
  2440. for(auto c : level.second)
  2441. {
  2442. if(h->getSlotFor(CreatureID(c)) != SlotID())
  2443. canRecruitCreatures = true;
  2444. }
  2445. }
  2446. return canRecruitCreatures;
  2447. }
  2448. case Obj::HILL_FORT:
  2449. {
  2450. for(auto slot : h->Slots())
  2451. {
  2452. if(slot.second->type->hasUpgrades())
  2453. return true; //TODO: check price?
  2454. }
  2455. return false;
  2456. }
  2457. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  2458. case Obj::MONOLITH_ONE_WAY_EXIT:
  2459. case Obj::MONOLITH_TWO_WAY:
  2460. case Obj::WHIRLPOOL:
  2461. return false;
  2462. case Obj::SCHOOL_OF_MAGIC:
  2463. case Obj::SCHOOL_OF_WAR:
  2464. {
  2465. if (ai->ah->freeGold() < 1000)
  2466. return false;
  2467. break;
  2468. }
  2469. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2470. if(h->level < 12)
  2471. return false;
  2472. break;
  2473. case Obj::TREE_OF_KNOWLEDGE:
  2474. {
  2475. TResources myRes = ai->ah->freeResources();
  2476. if(myRes[EGameResID::GOLD] < 2000 || myRes[EGameResID::GEMS] < 10)
  2477. return false;
  2478. break;
  2479. }
  2480. case Obj::MAGIC_WELL:
  2481. return h->mana < h->manaLimit();
  2482. case Obj::PRISON:
  2483. return ai->myCb->getHeroesInfo().size() < VLC->settings()->getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP);
  2484. case Obj::TAVERN:
  2485. {
  2486. //TODO: make AI actually recruit heroes
  2487. //TODO: only on request
  2488. if(ai->myCb->getHeroesInfo().size() >= VLC->settings()->getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP))
  2489. return false;
  2490. else if(ai->ah->freeGold() < GameConstants::HERO_GOLD_COST)
  2491. return false;
  2492. break;
  2493. }
  2494. case Obj::BOAT:
  2495. return false;
  2496. //Boats are handled by pathfinder
  2497. case Obj::EYE_OF_MAGI:
  2498. return false; //this object is useless to visit, but could be visited indefinitely
  2499. }
  2500. if(obj->wasVisited(*h)) //it must pointer to hero instance, heroPtr calls function wasVisited(ui8 player);
  2501. return false;
  2502. return true;
  2503. }