VCAI.cpp 89 KB

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