VCAI.cpp 79 KB

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