VCAI.cpp 88 KB

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