VCAI.cpp 97 KB

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