VCAI.cpp 88 KB

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