VCAI.cpp 101 KB

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