VCAI.cpp 82 KB

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