VCAI.cpp 87 KB

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