VCAI.cpp 99 KB

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