VCAI.cpp 89 KB

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