VCAI.cpp 83 KB

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