VCAI.cpp 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947
  1. /*
  2. * VCAI.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "VCAI.h"
  12. #include "FuzzyHelper.h"
  13. #include "ResourceManager.h"
  14. #include "BuildingManager.h"
  15. #include "Goals/Goals.h"
  16. #include "../../lib/UnlockGuard.h"
  17. #include "../../lib/mapObjects/MapObjects.h"
  18. #include "../../lib/CConfigHandler.h"
  19. #include "../../lib/CHeroHandler.h"
  20. #include "../../lib/CModHandler.h"
  21. #include "../../lib/CGameState.h"
  22. #include "../../lib/NetPacks.h"
  23. #include "../../lib/serializer/CTypeList.h"
  24. #include "../../lib/serializer/BinarySerializer.h"
  25. #include "../../lib/serializer/BinaryDeserializer.h"
  26. #include "AIhelper.h"
  27. #include "Engine/Nullkiller.h"
  28. extern FuzzyHelper * fh;
  29. class CGVisitableOPW;
  30. const double SAFE_ATTACK_CONSTANT = 1.5;
  31. //one thread may be turn of AI and another will be handling a side effect for AI2
  32. boost::thread_specific_ptr<CCallback> cb;
  33. boost::thread_specific_ptr<VCAI> ai;
  34. //std::map<int, std::map<int, int> > HeroView::infosCount;
  35. //helper RAII to manage global ai/cb ptrs
  36. struct SetGlobalState
  37. {
  38. SetGlobalState(VCAI * AI)
  39. {
  40. assert(!ai.get());
  41. assert(!cb.get());
  42. ai.reset(AI);
  43. cb.reset(AI->myCb.get());
  44. }
  45. ~SetGlobalState()
  46. {
  47. //TODO: how to handle rm? shouldn't be called after ai is destroyed, hopefully
  48. //TODO: to ensure that, make rm unique_ptr
  49. ai.release();
  50. cb.release();
  51. }
  52. };
  53. #define SET_GLOBAL_STATE(ai) SetGlobalState _hlpSetState(ai);
  54. #define NET_EVENT_HANDLER SET_GLOBAL_STATE(this)
  55. #define MAKING_TURN SET_GLOBAL_STATE(this)
  56. VCAI::VCAI()
  57. {
  58. LOG_TRACE(logAi);
  59. makingTurn = nullptr;
  60. destinationTeleport = ObjectInstanceID();
  61. destinationTeleportPos = int3(-1);
  62. ah = new AIhelper();
  63. ah->setAI(this);
  64. }
  65. VCAI::~VCAI()
  66. {
  67. delete ah;
  68. LOG_TRACE(logAi);
  69. finish();
  70. }
  71. void VCAI::availableCreaturesChanged(const CGDwelling * town)
  72. {
  73. LOG_TRACE(logAi);
  74. NET_EVENT_HANDLER;
  75. }
  76. void VCAI::heroMoved(const TryMoveHero & details)
  77. {
  78. LOG_TRACE(logAi);
  79. NET_EVENT_HANDLER;
  80. validateObject(details.id); //enemy hero may have left visible area
  81. auto hero = cb->getHero(details.id);
  82. const int3 from = CGHeroInstance::convertPosition(details.start, false);
  83. const int3 to = CGHeroInstance::convertPosition(details.end, false);
  84. const CGObjectInstance * o1 = vstd::frontOrNull(cb->getVisitableObjs(from));
  85. const CGObjectInstance * o2 = vstd::frontOrNull(cb->getVisitableObjs(to));
  86. if(details.result == TryMoveHero::TELEPORTATION)
  87. {
  88. auto t1 = dynamic_cast<const CGTeleport *>(o1);
  89. auto t2 = dynamic_cast<const CGTeleport *>(o2);
  90. if(t1 && t2)
  91. {
  92. if(cb->isTeleportChannelBidirectional(t1->channel))
  93. {
  94. if(o1->ID == Obj::SUBTERRANEAN_GATE && o1->ID == o2->ID) // We need to only add subterranean gates in knownSubterraneanGates. Used for features not yet ported to use teleport channels
  95. {
  96. knownSubterraneanGates[o1] = o2;
  97. knownSubterraneanGates[o2] = o1;
  98. logAi->debug("Found a pair of subterranean gates between %s and %s!", from.toString(), to.toString());
  99. }
  100. }
  101. }
  102. //FIXME: teleports are not correctly visited
  103. unreserveObject(hero, t1);
  104. unreserveObject(hero, t2);
  105. }
  106. else if(details.result == TryMoveHero::EMBARK && hero)
  107. {
  108. //make sure AI not attempt to visit used boat
  109. validateObject(hero->boat);
  110. }
  111. else if(details.result == TryMoveHero::DISEMBARK && o1)
  112. {
  113. auto boat = dynamic_cast<const CGBoat *>(o1);
  114. if(boat)
  115. addVisitableObj(boat);
  116. }
  117. }
  118. void VCAI::heroInGarrisonChange(const CGTownInstance * town)
  119. {
  120. LOG_TRACE(logAi);
  121. NET_EVENT_HANDLER;
  122. }
  123. void VCAI::centerView(int3 pos, int focusTime)
  124. {
  125. LOG_TRACE_PARAMS(logAi, "focusTime '%i'", focusTime);
  126. NET_EVENT_HANDLER;
  127. }
  128. void VCAI::artifactMoved(const ArtifactLocation & src, const ArtifactLocation & dst)
  129. {
  130. LOG_TRACE(logAi);
  131. NET_EVENT_HANDLER;
  132. }
  133. void VCAI::artifactAssembled(const ArtifactLocation & al)
  134. {
  135. LOG_TRACE(logAi);
  136. NET_EVENT_HANDLER;
  137. }
  138. void VCAI::showTavernWindow(const CGObjectInstance * townOrTavern)
  139. {
  140. LOG_TRACE(logAi);
  141. NET_EVENT_HANDLER;
  142. }
  143. void VCAI::showThievesGuildWindow(const CGObjectInstance * obj)
  144. {
  145. LOG_TRACE(logAi);
  146. NET_EVENT_HANDLER;
  147. }
  148. void VCAI::playerBlocked(int reason, bool start)
  149. {
  150. LOG_TRACE_PARAMS(logAi, "reason '%i', start '%i'", reason % start);
  151. NET_EVENT_HANDLER;
  152. if(start && reason == PlayerBlocked::UPCOMING_BATTLE)
  153. status.setBattle(UPCOMING_BATTLE);
  154. if(reason == PlayerBlocked::ONGOING_MOVEMENT)
  155. status.setMove(start);
  156. }
  157. void VCAI::showPuzzleMap()
  158. {
  159. LOG_TRACE(logAi);
  160. NET_EVENT_HANDLER;
  161. }
  162. void VCAI::showShipyardDialog(const IShipyard * obj)
  163. {
  164. LOG_TRACE(logAi);
  165. NET_EVENT_HANDLER;
  166. }
  167. void VCAI::gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult)
  168. {
  169. LOG_TRACE_PARAMS(logAi, "victoryLossCheckResult '%s'", victoryLossCheckResult.messageToSelf);
  170. NET_EVENT_HANDLER;
  171. logAi->debug("Player %d (%s): I heard that player %d (%s) %s.", playerID, playerID.getStr(), player, player.getStr(), (victoryLossCheckResult.victory() ? "won" : "lost"));
  172. if(player == playerID)
  173. {
  174. if(victoryLossCheckResult.victory())
  175. {
  176. logAi->debug("VCAI: I won! Incredible!");
  177. logAi->debug("Turn nr %d", myCb->getDate());
  178. }
  179. else
  180. {
  181. logAi->debug("VCAI: Player %d (%s) lost. It's me. What a disappointment! :(", player, player.getStr());
  182. }
  183. finish();
  184. }
  185. }
  186. void VCAI::artifactPut(const ArtifactLocation & al)
  187. {
  188. LOG_TRACE(logAi);
  189. NET_EVENT_HANDLER;
  190. }
  191. void VCAI::artifactRemoved(const ArtifactLocation & al)
  192. {
  193. LOG_TRACE(logAi);
  194. NET_EVENT_HANDLER;
  195. }
  196. void VCAI::artifactDisassembled(const ArtifactLocation & al)
  197. {
  198. LOG_TRACE(logAi);
  199. NET_EVENT_HANDLER;
  200. }
  201. void VCAI::heroVisit(const CGHeroInstance * visitor, const CGObjectInstance * visitedObj, bool start)
  202. {
  203. LOG_TRACE_PARAMS(logAi, "start '%i'; obj '%s'", start % (visitedObj ? visitedObj->getObjectName() : std::string("n/a")));
  204. NET_EVENT_HANDLER;
  205. if(start && visitedObj) //we can end visit with null object, anyway
  206. {
  207. markObjectVisited(visitedObj);
  208. unreserveObject(visitor, visitedObj);
  209. completeGoal(sptr(Goals::VisitObj(visitedObj->id.getNum()).sethero(visitor))); //we don't need to visit it anymore
  210. //TODO: what if we visited one-time visitable object that was reserved by another hero (shouldn't, but..)
  211. if (visitedObj->ID == Obj::HERO)
  212. {
  213. visitedHeroes[visitor].insert(HeroPtr(dynamic_cast<const CGHeroInstance *>(visitedObj)));
  214. }
  215. }
  216. status.heroVisit(visitedObj, start);
  217. }
  218. void VCAI::availableArtifactsChanged(const CGBlackMarket * bm)
  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. clearPathsInfo();
  236. }
  237. void VCAI::tileRevealed(const std::unordered_set<int3, ShashInt3> & pos)
  238. {
  239. LOG_TRACE(logAi);
  240. NET_EVENT_HANDLER;
  241. for(int3 tile : pos)
  242. {
  243. for(const CGObjectInstance * obj : myCb->getVisitableObjs(tile))
  244. addVisitableObj(obj);
  245. }
  246. clearPathsInfo();
  247. }
  248. void VCAI::heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query)
  249. {
  250. LOG_TRACE(logAi);
  251. NET_EVENT_HANDLER;
  252. auto firstHero = cb->getHero(hero1);
  253. auto secondHero = cb->getHero(hero2);
  254. status.addQuery(query, boost::str(boost::format("Exchange between heroes %s (%d) and %s (%d)") % firstHero->name % firstHero->tempOwner % secondHero->name % secondHero->tempOwner));
  255. requestActionASAP([=]()
  256. {
  257. float goalpriority1 = 0, goalpriority2 = 0;
  258. auto firstGoal = getGoal(firstHero);
  259. if(firstGoal->goalType == Goals::GATHER_ARMY)
  260. goalpriority1 = firstGoal->priority;
  261. auto secondGoal = getGoal(secondHero);
  262. if(secondGoal->goalType == Goals::GATHER_ARMY)
  263. goalpriority2 = secondGoal->priority;
  264. auto transferFrom2to1 = [this](const CGHeroInstance * h1, const CGHeroInstance * h2) -> void
  265. {
  266. this->pickBestCreatures(h1, h2);
  267. this->pickBestArtifacts(h1, h2);
  268. };
  269. //Do not attempt army or artifacts exchange if we visited ally player
  270. //Visits can still be useful if hero have skills like Scholar
  271. if(firstHero->tempOwner != secondHero->tempOwner)
  272. {
  273. logAi->debug("Heroes owned by different players. Do not exchange army or artifacts.");
  274. }
  275. else if(goalpriority1 > goalpriority2)
  276. {
  277. transferFrom2to1(firstHero, secondHero);
  278. }
  279. else if(goalpriority1 < goalpriority2)
  280. {
  281. transferFrom2to1(secondHero, firstHero);
  282. }
  283. else //regular criteria
  284. {
  285. if(firstHero->getFightingStrength() > secondHero->getFightingStrength() && canGetArmy(firstHero, secondHero))
  286. transferFrom2to1(firstHero, secondHero);
  287. else if(canGetArmy(secondHero, firstHero))
  288. transferFrom2to1(secondHero, firstHero);
  289. }
  290. completeGoal(sptr(Goals::VisitHero(firstHero->id.getNum()))); //TODO: what if we were visited by other hero in the meantime?
  291. completeGoal(sptr(Goals::VisitHero(secondHero->id.getNum())));
  292. answerQuery(query, 0);
  293. });
  294. }
  295. void VCAI::heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val)
  296. {
  297. LOG_TRACE_PARAMS(logAi, "which '%i', val '%i'", which % val);
  298. NET_EVENT_HANDLER;
  299. }
  300. void VCAI::showRecruitmentDialog(const CGDwelling * dwelling, const CArmedInstance * dst, int level)
  301. {
  302. LOG_TRACE_PARAMS(logAi, "level '%i'", level);
  303. NET_EVENT_HANDLER;
  304. }
  305. void VCAI::heroMovePointsChanged(const CGHeroInstance * hero)
  306. {
  307. LOG_TRACE(logAi);
  308. NET_EVENT_HANDLER;
  309. }
  310. void VCAI::garrisonsChanged(ObjectInstanceID id1, ObjectInstanceID id2)
  311. {
  312. LOG_TRACE(logAi);
  313. NET_EVENT_HANDLER;
  314. }
  315. void VCAI::newObject(const CGObjectInstance * obj)
  316. {
  317. LOG_TRACE(logAi);
  318. NET_EVENT_HANDLER;
  319. if(obj->isVisitable())
  320. addVisitableObj(obj);
  321. }
  322. //to prevent AI from accessing objects that got deleted while they became invisible (Cover of Darkness, enemy hero moved etc.) below code allows AI to know deletion of objects out of sight
  323. //see: RemoveObject::applyFirstCl, to keep AI "not cheating" do not use advantage of this and use this function just to prevent crashes
  324. void VCAI::objectRemoved(const CGObjectInstance * obj)
  325. {
  326. LOG_TRACE(logAi);
  327. NET_EVENT_HANDLER;
  328. vstd::erase_if_present(visitableObjs, obj);
  329. vstd::erase_if_present(alreadyVisited, obj);
  330. for(auto h : cb->getHeroesInfo())
  331. unreserveObject(h, obj);
  332. std::function<bool(const Goals::TSubgoal &)> checkRemovalValidity = [&](const Goals::TSubgoal & x) -> bool
  333. {
  334. if((x->goalType == Goals::VISIT_OBJ) && (x->objid == obj->id.getNum()))
  335. return true;
  336. else if(x->parent && checkRemovalValidity(x->parent)) //repeat this lambda check recursively on parent goal
  337. return true;
  338. else
  339. return false;
  340. };
  341. //clear VCAI / main loop caches
  342. vstd::erase_if(lockedHeroes, [&](const std::pair<HeroPtr, Goals::TSubgoal> & x) -> bool
  343. {
  344. return checkRemovalValidity(x.second);
  345. });
  346. vstd::erase_if(ultimateGoalsFromBasic, [&](const std::pair<Goals::TSubgoal, Goals::TGoalVec> & x) -> bool
  347. {
  348. return checkRemovalValidity(x.first);
  349. });
  350. vstd::erase_if(basicGoals, checkRemovalValidity);
  351. vstd::erase_if(goalsToAdd, checkRemovalValidity);
  352. vstd::erase_if(goalsToRemove, checkRemovalValidity);
  353. for(auto goal : ultimateGoalsFromBasic)
  354. vstd::erase_if(goal.second, checkRemovalValidity);
  355. //clear resource manager goal cache
  356. ah->removeOutdatedObjectives(checkRemovalValidity);
  357. //TODO: Find better way to handle hero boat removal
  358. if(auto hero = dynamic_cast<const CGHeroInstance *>(obj))
  359. {
  360. if(hero->boat)
  361. {
  362. vstd::erase_if_present(visitableObjs, hero->boat);
  363. vstd::erase_if_present(alreadyVisited, hero->boat);
  364. for(auto h : cb->getHeroesInfo())
  365. unreserveObject(h, hero->boat);
  366. }
  367. }
  368. //TODO
  369. //there are other places where CGObjectinstance ptrs are stored...
  370. //
  371. if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
  372. {
  373. lostHero(cb->getHero(obj->id)); //we can promote, since objectRemoved is called just before actual deletion
  374. }
  375. }
  376. void VCAI::showHillFortWindow(const CGObjectInstance * object, const CGHeroInstance * visitor)
  377. {
  378. LOG_TRACE(logAi);
  379. NET_EVENT_HANDLER;
  380. requestActionASAP([=]()
  381. {
  382. makePossibleUpgrades(visitor);
  383. });
  384. }
  385. void VCAI::playerBonusChanged(const Bonus & bonus, bool gain)
  386. {
  387. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  388. NET_EVENT_HANDLER;
  389. }
  390. void VCAI::heroCreated(const CGHeroInstance * h)
  391. {
  392. LOG_TRACE(logAi);
  393. if(h->visitedTown)
  394. townVisitsThisWeek[HeroPtr(h)].insert(h->visitedTown);
  395. NET_EVENT_HANDLER;
  396. }
  397. void VCAI::advmapSpellCast(const CGHeroInstance * caster, int spellID)
  398. {
  399. LOG_TRACE_PARAMS(logAi, "spellID '%i", spellID);
  400. NET_EVENT_HANDLER;
  401. }
  402. void VCAI::showInfoDialog(const std::string & text, const std::vector<Component> & components, int soundID)
  403. {
  404. LOG_TRACE_PARAMS(logAi, "soundID '%i'", soundID);
  405. NET_EVENT_HANDLER;
  406. }
  407. void VCAI::requestRealized(PackageApplied * pa)
  408. {
  409. LOG_TRACE(logAi);
  410. NET_EVENT_HANDLER;
  411. if(status.haveTurn())
  412. {
  413. if(pa->packType == typeList.getTypeID<EndTurn>())
  414. {
  415. if(pa->result)
  416. status.madeTurn();
  417. }
  418. }
  419. if(pa->packType == typeList.getTypeID<QueryReply>())
  420. {
  421. status.receivedAnswerConfirmation(pa->requestID, pa->result);
  422. }
  423. }
  424. void VCAI::receivedResource()
  425. {
  426. LOG_TRACE(logAi);
  427. NET_EVENT_HANDLER;
  428. }
  429. void VCAI::showUniversityWindow(const IMarket * market, const CGHeroInstance * visitor)
  430. {
  431. LOG_TRACE(logAi);
  432. NET_EVENT_HANDLER;
  433. }
  434. void VCAI::heroManaPointsChanged(const CGHeroInstance * hero)
  435. {
  436. LOG_TRACE(logAi);
  437. NET_EVENT_HANDLER;
  438. }
  439. void VCAI::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  440. {
  441. LOG_TRACE_PARAMS(logAi, "which '%d', val '%d'", which % val);
  442. NET_EVENT_HANDLER;
  443. }
  444. void VCAI::battleResultsApplied()
  445. {
  446. LOG_TRACE(logAi);
  447. NET_EVENT_HANDLER;
  448. assert(status.getBattle() == ENDING_BATTLE);
  449. status.setBattle(NO_BATTLE);
  450. }
  451. void VCAI::objectPropertyChanged(const SetObjectProperty * sop)
  452. {
  453. LOG_TRACE(logAi);
  454. NET_EVENT_HANDLER;
  455. if(sop->what == ObjProperty::OWNER)
  456. {
  457. if(myCb->getPlayerRelations(playerID, (PlayerColor)sop->val) == PlayerRelations::ENEMIES)
  458. {
  459. //we want to visit objects owned by oppponents
  460. auto obj = myCb->getObj(sop->id, false);
  461. if(obj)
  462. {
  463. addVisitableObj(obj); // TODO: Remove once save compatability broken. In past owned objects were removed from this set
  464. vstd::erase_if_present(alreadyVisited, obj);
  465. }
  466. }
  467. }
  468. }
  469. void VCAI::buildChanged(const CGTownInstance * town, BuildingID buildingID, int what)
  470. {
  471. LOG_TRACE_PARAMS(logAi, "what '%i'", what);
  472. NET_EVENT_HANDLER;
  473. if(town->getOwner() == playerID && what == 1) //built
  474. completeGoal(sptr(Goals::BuildThis(buildingID, town)));
  475. }
  476. void VCAI::heroBonusChanged(const CGHeroInstance * hero, const Bonus & bonus, bool gain)
  477. {
  478. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  479. NET_EVENT_HANDLER;
  480. }
  481. void VCAI::showMarketWindow(const IMarket * market, const CGHeroInstance * visitor)
  482. {
  483. LOG_TRACE(logAi);
  484. NET_EVENT_HANDLER;
  485. }
  486. void VCAI::showWorldViewEx(const std::vector<ObjectPosInfo> & objectPositions)
  487. {
  488. //TODO: AI support for ViewXXX spell
  489. LOG_TRACE(logAi);
  490. NET_EVENT_HANDLER;
  491. }
  492. void VCAI::init(std::shared_ptr<CCallback> CB)
  493. {
  494. LOG_TRACE(logAi);
  495. myCb = CB;
  496. cbc = CB;
  497. ah->init(CB.get());
  498. NET_EVENT_HANDLER; //sets ah->rm->cb
  499. playerID = *myCb->getMyColor();
  500. myCb->waitTillRealize = true;
  501. myCb->unlockGsWhenWaiting = true;
  502. if(!fh)
  503. fh = new FuzzyHelper();
  504. if(playerID.getStr(false) == "blue")
  505. {
  506. nullkiller.reset(new Nullkiller());
  507. }
  508. retrieveVisitableObjs();
  509. }
  510. void VCAI::yourTurn()
  511. {
  512. LOG_TRACE(logAi);
  513. NET_EVENT_HANDLER;
  514. status.startedTurn();
  515. makingTurn = make_unique<boost::thread>(&VCAI::makeTurn, this);
  516. }
  517. void VCAI::heroGotLevel(const CGHeroInstance * hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill> & skills, QueryID queryID)
  518. {
  519. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  520. NET_EVENT_HANDLER;
  521. status.addQuery(queryID, boost::str(boost::format("Hero %s got level %d") % hero->name % hero->level));
  522. requestActionASAP([=](){ answerQuery(queryID, 0); });
  523. }
  524. void VCAI::commanderGotLevel(const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID)
  525. {
  526. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  527. NET_EVENT_HANDLER;
  528. status.addQuery(queryID, boost::str(boost::format("Commander %s of %s got level %d") % commander->name % commander->armyObj->nodeName() % (int)commander->level));
  529. requestActionASAP([=](){ answerQuery(queryID, 0); });
  530. }
  531. void VCAI::showBlockingDialog(const std::string & text, const std::vector<Component> & components, QueryID askID, const int soundID, bool selection, bool cancel)
  532. {
  533. LOG_TRACE_PARAMS(logAi, "text '%s', askID '%i', soundID '%i', selection '%i', cancel '%i'", text % askID % soundID % selection % cancel);
  534. NET_EVENT_HANDLER;
  535. int sel = 0;
  536. status.addQuery(askID, boost::str(boost::format("Blocking dialog query with %d components - %s")
  537. % components.size() % text));
  538. if(selection) //select from multiple components -> take the last one (they're indexed [1-size])
  539. sel = components.size();
  540. if(!selection && cancel) //yes&no -> always answer yes, we are a brave AI :)
  541. sel = 1;
  542. requestActionASAP([=]()
  543. {
  544. answerQuery(askID, sel);
  545. });
  546. }
  547. void VCAI::showTeleportDialog(TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID)
  548. {
  549. // LOG_TRACE_PARAMS(logAi, "askID '%i', exits '%s'", askID % exits);
  550. NET_EVENT_HANDLER;
  551. status.addQuery(askID, boost::str(boost::format("Teleport dialog query with %d exits")
  552. % exits.size()));
  553. int choosenExit = -1;
  554. if(impassable)
  555. {
  556. knownTeleportChannels[channel]->passability = TeleportChannel::IMPASSABLE;
  557. }
  558. else if(destinationTeleport != ObjectInstanceID() && destinationTeleportPos.valid())
  559. {
  560. auto neededExit = std::make_pair(destinationTeleport, destinationTeleportPos);
  561. if(destinationTeleport != ObjectInstanceID() && vstd::contains(exits, neededExit))
  562. choosenExit = vstd::find_pos(exits, neededExit);
  563. }
  564. for(auto exit : exits)
  565. {
  566. if(status.channelProbing() && exit.first == destinationTeleport)
  567. {
  568. choosenExit = vstd::find_pos(exits, exit);
  569. break;
  570. }
  571. else
  572. {
  573. // TODO: Implement checking if visiting that teleport will uncovert any FoW
  574. // So far this is the best option to handle decision about probing
  575. auto obj = cb->getObj(exit.first, false);
  576. if(obj == nullptr && !vstd::contains(teleportChannelProbingList, exit.first))
  577. {
  578. if(exit.first != destinationTeleport)
  579. teleportChannelProbingList.push_back(exit.first);
  580. }
  581. }
  582. }
  583. requestActionASAP([=]()
  584. {
  585. answerQuery(askID, choosenExit);
  586. });
  587. }
  588. void VCAI::showGarrisonDialog(const CArmedInstance * up, const CGHeroInstance * down, bool removableUnits, QueryID queryID)
  589. {
  590. LOG_TRACE_PARAMS(logAi, "removableUnits '%i', queryID '%i'", removableUnits % queryID);
  591. NET_EVENT_HANDLER;
  592. std::string s1 = up ? up->nodeName() : "NONE";
  593. std::string s2 = down ? down->nodeName() : "NONE";
  594. status.addQuery(queryID, boost::str(boost::format("Garrison dialog with %s and %s") % s1 % s2));
  595. //you can't request action from action-response thread
  596. requestActionASAP([=]()
  597. {
  598. if(removableUnits)
  599. pickBestCreatures(down, up);
  600. answerQuery(queryID, 0);
  601. });
  602. }
  603. void VCAI::showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects)
  604. {
  605. NET_EVENT_HANDLER;
  606. status.addQuery(askID, "Map object select query");
  607. requestActionASAP([=](){ answerQuery(askID, selectedObject.getNum()); });
  608. }
  609. void VCAI::saveGame(BinarySerializer & h, const int version)
  610. {
  611. LOG_TRACE_PARAMS(logAi, "version '%i'", version);
  612. NET_EVENT_HANDLER;
  613. validateVisitableObjs();
  614. #if 0
  615. //disabled due to issue 2890
  616. registerGoals(h);
  617. #endif // 0
  618. CAdventureAI::saveGame(h, version);
  619. serializeInternal(h, version);
  620. }
  621. void VCAI::loadGame(BinaryDeserializer & h, const int version)
  622. {
  623. LOG_TRACE_PARAMS(logAi, "version '%i'", version);
  624. //NET_EVENT_HANDLER;
  625. #if 0
  626. //disabled due to issue 2890
  627. registerGoals(h);
  628. #endif // 0
  629. CAdventureAI::loadGame(h, version);
  630. serializeInternal(h, version);
  631. }
  632. void makePossibleUpgrades(const CArmedInstance * obj)
  633. {
  634. if(!obj)
  635. return;
  636. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  637. {
  638. if(const CStackInstance * s = obj->getStackPtr(SlotID(i)))
  639. {
  640. UpgradeInfo ui;
  641. cb->getUpgradeInfo(obj, SlotID(i), ui);
  642. if(ui.oldID >= 0 && cb->getResourceAmount().canAfford(ui.cost[0] * s->count))
  643. {
  644. cb->upgradeCreature(obj, SlotID(i), ui.newID[0]);
  645. }
  646. }
  647. }
  648. }
  649. void VCAI::makeTurn()
  650. {
  651. MAKING_TURN;
  652. auto day = cb->getDate(Date::EDateType::DAY);
  653. logAi->info("Player %d (%s) starting turn, day %d", playerID, playerID.getStr(), day);
  654. boost::shared_lock<boost::shared_mutex> gsLock(CGameState::mutex);
  655. setThreadName("VCAI::makeTurn");
  656. switch(cb->getDate(Date::DAY_OF_WEEK))
  657. {
  658. case 1:
  659. {
  660. townVisitsThisWeek.clear();
  661. std::vector<const CGObjectInstance *> objs;
  662. retrieveVisitableObjs(objs, true);
  663. for(const CGObjectInstance * obj : objs)
  664. {
  665. if(isWeeklyRevisitable(obj))
  666. {
  667. addVisitableObj(obj);
  668. vstd::erase_if_present(alreadyVisited, obj);
  669. }
  670. }
  671. break;
  672. }
  673. }
  674. markHeroAbleToExplore(primaryHero());
  675. visitedHeroes.clear();
  676. if(cb->getDate(Date::DAY) == 1)
  677. {
  678. retrieveVisitableObjs();
  679. }
  680. try
  681. {
  682. if(nullkiller)
  683. {
  684. nullkiller->makeTurn();
  685. }
  686. else
  687. {
  688. //it looks messy here, but it's better to have armed heroes before attempting realizing goals
  689. for(const CGTownInstance * t : cb->getTownsInfo())
  690. moveCreaturesToHero(t);
  691. mainLoop();
  692. /*Below function is also responsible for hero movement via internal wander function. By design it is separate logic for heroes that have nothing to do.
  693. Heroes that were not picked by striveToGoal(sptr(Goals::Win())); recently (so they do not have new goals and cannot continue/reevaluate previously locked goals) will do logic in wander().*/
  694. performTypicalActions();
  695. }
  696. //for debug purpose
  697. for (auto h : cb->getHeroesInfo())
  698. {
  699. if (h->movement)
  700. logAi->warn("Hero %s has %d MP left", h->name, h->movement);
  701. }
  702. }
  703. catch (boost::thread_interrupted & e)
  704. {
  705. logAi->debug("Making turn thread has been interrupted. We'll end without calling endTurn.");
  706. return;
  707. }
  708. catch (std::exception & e)
  709. {
  710. logAi->debug("Making turn thread has caught an exception: %s", e.what());
  711. }
  712. endTurn();
  713. }
  714. std::vector<HeroPtr> VCAI::getMyHeroes() const
  715. {
  716. std::vector<HeroPtr> ret;
  717. for(auto h : cb->getHeroesInfo())
  718. {
  719. ret.push_back(h);
  720. }
  721. return ret;
  722. }
  723. void VCAI::mainLoop()
  724. {
  725. std::vector<Goals::TSubgoal> elementarGoals; //no duplicates allowed (operator ==)
  726. basicGoals.clear();
  727. validateVisitableObjs();
  728. //get all potential and saved goals
  729. //TODO: not lose
  730. basicGoals.push_back(sptr(Goals::Win()));
  731. for (auto goalPair : lockedHeroes)
  732. {
  733. fh->setPriority(goalPair.second); //re-evaluate, as heroes moved in the meantime
  734. basicGoals.push_back(goalPair.second);
  735. }
  736. if (ah->hasTasksLeft())
  737. basicGoals.push_back(ah->whatToDo());
  738. for (auto quest : myCb->getMyQuests())
  739. {
  740. basicGoals.push_back(sptr(Goals::CompleteQuest(quest)));
  741. }
  742. basicGoals.push_back(sptr(Goals::Build()));
  743. invalidPathHeroes.clear();
  744. while (basicGoals.size())
  745. {
  746. vstd::removeDuplicates(basicGoals); //TODO: container which does this automagically without has would be nice
  747. goalsToAdd.clear();
  748. goalsToRemove.clear();
  749. elementarGoals.clear();
  750. ultimateGoalsFromBasic.clear();
  751. ah->updatePaths(getMyHeroes());
  752. logAi->debug("Main loop: decomposing %i basic goals", basicGoals.size());
  753. for (auto basicGoal : basicGoals)
  754. {
  755. logAi->debug("Main loop: decomposing basic goal %s", basicGoal->name());
  756. auto goalToDecompose = basicGoal;
  757. Goals::TSubgoal elementarGoal = sptr(Goals::Invalid());
  758. int maxAbstractGoals = 10;
  759. while (!elementarGoal->isElementar && maxAbstractGoals)
  760. {
  761. try
  762. {
  763. elementarGoal = decomposeGoal(goalToDecompose);
  764. }
  765. catch (goalFulfilledException & e)
  766. {
  767. //it is impossible to continue some goals (like exploration, for example)
  768. //complete abstract goal for now, but maybe main goal finds another path
  769. logAi->debug("Goal %s decomposition failed: goal was completed as much as possible", e.goal->name());
  770. completeGoal(e.goal); //put in goalsToRemove
  771. break;
  772. }
  773. catch(cannotFulfillGoalException & e)
  774. {
  775. //it is impossible to continue some goals (like exploration, for example)
  776. //complete abstract goal for now, but maybe main goal finds another path
  777. goalsToRemove.push_back(basicGoal);
  778. logAi->debug("Goal %s decomposition failed: %s", goalToDecompose->name(), e.what());
  779. break;
  780. }
  781. catch (std::exception & e) //decomposition failed, which means we can't decompose entire tree
  782. {
  783. goalsToRemove.push_back(basicGoal);
  784. logAi->debug("Goal %s decomposition failed: %s", basicGoal->name(), e.what());
  785. break;
  786. }
  787. if (elementarGoal->isAbstract) //we can decompose it further
  788. {
  789. goalsToAdd.push_back(elementarGoal);
  790. //decompose further now - this is necesssary if we can't add over 10 goals in the pool
  791. goalToDecompose = elementarGoal;
  792. //there is a risk of infinite abstract goal loop, though it indicates failed logic
  793. maxAbstractGoals--;
  794. }
  795. else if (elementarGoal->isElementar) //should be
  796. {
  797. logAi->debug("Found elementar goal %s", elementarGoal->name());
  798. elementarGoals.push_back(elementarGoal);
  799. ultimateGoalsFromBasic[elementarGoal].push_back(goalToDecompose); //TODO: how about indirect basicGoal?
  800. break;
  801. }
  802. else //should never be here
  803. throw cannotFulfillGoalException("Goal %s is neither abstract nor elementar!" + basicGoal->name());
  804. }
  805. }
  806. logAi->trace("Main loop: selecting best elementar goal");
  807. //now choose one elementar goal to realize
  808. Goals::TGoalVec possibleGoals(elementarGoals.begin(), elementarGoals.end()); //copy to vector
  809. Goals::TSubgoal goalToRealize = sptr(Goals::Invalid());
  810. while (possibleGoals.size())
  811. {
  812. //allow assign goals to heroes with 0 movement, but don't realize them
  813. //maybe there are beter ones left
  814. auto bestGoal = fh->chooseSolution(possibleGoals);
  815. if (bestGoal->hero) //lock this hero to fulfill goal
  816. {
  817. setGoal(bestGoal->hero, bestGoal);
  818. if (!bestGoal->hero->movement || vstd::contains(invalidPathHeroes, bestGoal->hero))
  819. {
  820. if (!vstd::erase_if_present(possibleGoals, bestGoal))
  821. {
  822. logAi->error("erase_if_preset failed? Something very wrong!");
  823. break;
  824. }
  825. continue; //chose next from the list
  826. }
  827. }
  828. goalToRealize = bestGoal; //we found our goal to execute
  829. break;
  830. }
  831. //realize best goal
  832. if (!goalToRealize->invalid())
  833. {
  834. logAi->debug("Trying to realize %s (value %2.3f)", goalToRealize->name(), goalToRealize->priority);
  835. try
  836. {
  837. boost::this_thread::interruption_point();
  838. goalToRealize->accept(this); //visitor pattern
  839. boost::this_thread::interruption_point();
  840. }
  841. catch (boost::thread_interrupted & e)
  842. {
  843. logAi->debug("Player %d: Making turn thread received an interruption!", playerID);
  844. throw; //rethrow, we want to truly end this thread
  845. }
  846. catch (goalFulfilledException & e)
  847. {
  848. //the sub-goal was completed successfully
  849. completeGoal(e.goal);
  850. //local goal was also completed?
  851. completeGoal(goalToRealize);
  852. // remove abstract visit tile if we completed the elementar one
  853. vstd::erase_if_present(goalsToAdd, goalToRealize);
  854. }
  855. catch (std::exception & e)
  856. {
  857. logAi->debug("Failed to realize subgoal of type %s, I will stop.", goalToRealize->name());
  858. logAi->debug("The error message was: %s", e.what());
  859. //erase base goal if we failed to execute decomposed goal
  860. for (auto basicGoal : ultimateGoalsFromBasic[goalToRealize])
  861. goalsToRemove.push_back(basicGoal);
  862. // sometimes resource manager contains an elementar goal which is not able to execute anymore and just fails each turn.
  863. ai->ah->notifyGoalCompleted(goalToRealize);
  864. //we failed to realize best goal, but maybe others are still possible?
  865. }
  866. //remove goals we couldn't decompose
  867. for (auto goal : goalsToRemove)
  868. vstd::erase_if_present(basicGoals, goal);
  869. //add abstract goals
  870. boost::sort(goalsToAdd, [](const Goals::TSubgoal & lhs, const Goals::TSubgoal & rhs) -> bool
  871. {
  872. return lhs->priority > rhs->priority; //highest priority at the beginning
  873. });
  874. //max number of goals = 10
  875. int i = 0;
  876. while (basicGoals.size() < 10 && goalsToAdd.size() > i)
  877. {
  878. if (!vstd::contains(basicGoals, goalsToAdd[i])) //don't add duplicates
  879. basicGoals.push_back(goalsToAdd[i]);
  880. i++;
  881. }
  882. }
  883. else //no elementar goals possible
  884. {
  885. logAi->debug("Goal decomposition exhausted");
  886. break;
  887. }
  888. }
  889. }
  890. void VCAI::performObjectInteraction(const CGObjectInstance * obj, HeroPtr h)
  891. {
  892. LOG_TRACE_PARAMS(logAi, "Hero %s and object %s at %s", h->name % obj->getObjectName() % obj->pos.toString());
  893. switch(obj->ID)
  894. {
  895. case Obj::CREATURE_GENERATOR1:
  896. recruitCreatures(dynamic_cast<const CGDwelling *>(obj), h.get());
  897. checkHeroArmy(h);
  898. break;
  899. case Obj::TOWN:
  900. moveCreaturesToHero(dynamic_cast<const CGTownInstance *>(obj));
  901. if(h->visitedTown) //we are inside, not just attacking
  902. {
  903. townVisitsThisWeek[h].insert(h->visitedTown);
  904. if(!h->hasSpellbook() && ah->freeGold() >= GameConstants::SPELLBOOK_GOLD_COST)
  905. {
  906. if(h->visitedTown->hasBuilt(BuildingID::MAGES_GUILD_1))
  907. cb->buyArtifact(h.get(), ArtifactID::SPELLBOOK);
  908. }
  909. }
  910. break;
  911. }
  912. completeGoal(sptr(Goals::VisitObj(obj->id.getNum()).sethero(h)));
  913. }
  914. void VCAI::moveCreaturesToHero(const CGTownInstance * t)
  915. {
  916. if(t->visitingHero && t->armedGarrison() && t->visitingHero->tempOwner == t->tempOwner)
  917. {
  918. pickBestCreatures(t->visitingHero, t);
  919. }
  920. }
  921. bool VCAI::canGetArmy(const CGHeroInstance * army, const CGHeroInstance * source)
  922. {
  923. //TODO: merge with pickBestCreatures
  924. //if (ai->primaryHero().h == source)
  925. if(army->tempOwner != source->tempOwner)
  926. {
  927. logAi->error("Why are we even considering exchange between heroes from different players?");
  928. return false;
  929. }
  930. const CArmedInstance * armies[] = {army, source};
  931. //we calculate total strength for each creature type available in armies
  932. std::map<const CCreature *, int> creToPower;
  933. for(auto armyPtr : armies)
  934. {
  935. for(auto & i : armyPtr->Slots())
  936. {
  937. creToPower[i.second->type] += i.second->getPower();
  938. }
  939. }
  940. //TODO - consider more than just power (ie morale penalty, hero specialty in certain stacks, etc)
  941. int armySize = creToPower.size();
  942. armySize = std::min(armySize, GameConstants::ARMY_SIZE);
  943. std::vector<const CCreature *> bestArmy; //types that'll be in final dst army
  944. for(int i = 0; i < armySize; i++) //pick the creatures from which we can get most power, as many as dest can fit
  945. {
  946. typedef const std::pair<const CCreature *, int> & CrePowerPair;
  947. auto creIt = boost::max_element(creToPower, [](CrePowerPair lhs, CrePowerPair rhs)
  948. {
  949. return lhs.second < rhs.second;
  950. });
  951. bestArmy.push_back(creIt->first);
  952. creToPower.erase(creIt);
  953. if(creToPower.empty())
  954. break;
  955. }
  956. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  957. for(int i = 0; i < bestArmy.size(); i++) //i-th strongest creature type will go to i-th slot
  958. {
  959. for(auto armyPtr : armies)
  960. {
  961. for(int j = 0; j < GameConstants::ARMY_SIZE; j++)
  962. {
  963. if(armyPtr->getCreature(SlotID(j)) == bestArmy[i] && armyPtr != army) //it's a searched creature not in dst ARMY
  964. {
  965. if(!(armyPtr->needsLastStack() && (armyPtr->stacksCount() == 1) && armyPtr->getStackCount(SlotID(j)) < 2)) //can't take away or split last creature
  966. return true; //at least one exchange will be performed
  967. else
  968. return false; //no further exchange possible
  969. }
  970. }
  971. }
  972. }
  973. return false;
  974. }
  975. void VCAI::pickBestCreatures(const CArmedInstance * destinationArmy, const CArmedInstance * source)
  976. {
  977. const CArmedInstance * armies[] = {destinationArmy, source};
  978. //we calculate total strength for each creature type available in armies
  979. std::map<const CCreature *, int> creToPower;
  980. for(auto armyPtr : armies)
  981. {
  982. for(auto & i : armyPtr->Slots())
  983. {
  984. creToPower[i.second->type] += i.second->getPower();
  985. }
  986. }
  987. //TODO - consider more than just power (ie morale penalty, hero specialty in certain stacks, etc)
  988. int armySize = creToPower.size();
  989. armySize = std::min(armySize, GameConstants::ARMY_SIZE);
  990. std::vector<const CCreature *> bestArmy; //types that'll be in final dst army
  991. for(int i = 0; i < armySize; i++) //pick the creatures from which we can get most power, as many as dest can fit
  992. {
  993. typedef const std::pair<const CCreature *, int> & CrePowerPair;
  994. auto creIt = boost::max_element(creToPower, [](CrePowerPair lhs, CrePowerPair rhs)
  995. {
  996. return lhs.second < rhs.second;
  997. });
  998. bestArmy.push_back(creIt->first);
  999. creToPower.erase(creIt);
  1000. if(creToPower.empty())
  1001. break;
  1002. }
  1003. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  1004. for(int i = 0; i < bestArmy.size(); i++) //i-th strongest creature type will go to i-th slot
  1005. {
  1006. for(auto armyPtr : armies)
  1007. {
  1008. for(int j = 0; j < GameConstants::ARMY_SIZE; j++)
  1009. {
  1010. if(armyPtr->getCreature(SlotID(j)) == bestArmy[i] && (i != j || armyPtr != destinationArmy)) //it's a searched creature not in dst SLOT
  1011. {
  1012. if(!(armyPtr->needsLastStack() && armyPtr->stacksCount() == 1)) //can't take away last creature without split
  1013. {
  1014. cb->mergeOrSwapStacks(armyPtr, destinationArmy, SlotID(j), SlotID(i));
  1015. }
  1016. else
  1017. {
  1018. //TODO: Improve logic by splitting weakest creature, instead of creature that becomes last stack
  1019. SlotID sourceSlot = SlotID(j);
  1020. auto lastStackCount = armyPtr->getStackCount(sourceSlot);
  1021. if(lastStackCount > 1) //we can perform exchange if we need creature and split is possible
  1022. {
  1023. SlotID destinationSlot = SlotID(i);
  1024. //check if there are some creatures of same type in destination army slots - add to them instead of first available empty slot if possible
  1025. for(int candidateSlot = 0; candidateSlot < GameConstants::ARMY_SIZE; candidateSlot++)
  1026. {
  1027. auto creatureInSlot = destinationArmy->getCreature(SlotID(candidateSlot));
  1028. if(creatureInSlot && (creatureInSlot->idNumber == armyPtr->getCreature(SlotID(j))->idNumber))
  1029. {
  1030. destinationSlot = SlotID(candidateSlot);
  1031. break;
  1032. }
  1033. }
  1034. //last cb->splitStack argument is total amount of creatures expected after exchange so if slot is not empty we need to add to existing creatures
  1035. auto destinationSlotCreatureCount = destinationArmy->getStackCount(destinationSlot);
  1036. cb->splitStack(armyPtr, destinationArmy, sourceSlot, destinationSlot, lastStackCount + destinationSlotCreatureCount - 1);
  1037. }
  1038. }
  1039. }
  1040. }
  1041. }
  1042. }
  1043. //TODO - having now strongest possible army, we may want to think about arranging stacks
  1044. auto hero = dynamic_cast<const CGHeroInstance *>(destinationArmy);
  1045. if(hero)
  1046. checkHeroArmy(hero);
  1047. }
  1048. void VCAI::pickBestArtifacts(const CGHeroInstance * h, const CGHeroInstance * other)
  1049. {
  1050. auto equipBest = [](const CGHeroInstance * h, const CGHeroInstance * otherh, bool giveStuffToFirstHero) -> void
  1051. {
  1052. bool changeMade = false;
  1053. do
  1054. {
  1055. changeMade = false;
  1056. //we collect gear always in same order
  1057. std::vector<ArtifactLocation> allArtifacts;
  1058. if(giveStuffToFirstHero)
  1059. {
  1060. for(auto p : h->artifactsWorn)
  1061. {
  1062. if(p.second.artifact)
  1063. allArtifacts.push_back(ArtifactLocation(h, p.first));
  1064. }
  1065. }
  1066. for(auto slot : h->artifactsInBackpack)
  1067. allArtifacts.push_back(ArtifactLocation(h, h->getArtPos(slot.artifact)));
  1068. if(otherh)
  1069. {
  1070. for(auto p : otherh->artifactsWorn)
  1071. {
  1072. if(p.second.artifact)
  1073. allArtifacts.push_back(ArtifactLocation(otherh, p.first));
  1074. }
  1075. for(auto slot : otherh->artifactsInBackpack)
  1076. allArtifacts.push_back(ArtifactLocation(otherh, otherh->getArtPos(slot.artifact)));
  1077. }
  1078. //we give stuff to one hero or another, depending on giveStuffToFirstHero
  1079. const CGHeroInstance * target = nullptr;
  1080. if(giveStuffToFirstHero || !otherh)
  1081. target = h;
  1082. else
  1083. target = otherh;
  1084. for(auto location : allArtifacts)
  1085. {
  1086. if(location.relatedObj() == target && location.slot < ArtifactPosition::AFTER_LAST)
  1087. continue; //don't reequip artifact we already wear
  1088. if(location.slot == ArtifactPosition::MACH4) // don't attempt to move catapult
  1089. continue;
  1090. auto s = location.getSlot();
  1091. if(!s || s->locked) //we can't move locks
  1092. continue;
  1093. auto artifact = s->artifact;
  1094. if(!artifact)
  1095. continue;
  1096. //FIXME: why are the above possible to be null?
  1097. bool emptySlotFound = false;
  1098. for(auto slot : artifact->artType->possibleSlots.at(target->bearerType()))
  1099. {
  1100. ArtifactLocation destLocation(target, slot);
  1101. if(target->isPositionFree(slot) && artifact->canBePutAt(destLocation, true)) //combined artifacts are not always allowed to move
  1102. {
  1103. cb->swapArtifacts(location, destLocation); //just put into empty slot
  1104. emptySlotFound = true;
  1105. changeMade = true;
  1106. break;
  1107. }
  1108. }
  1109. if(!emptySlotFound) //try to put that atifact in already occupied slot
  1110. {
  1111. for(auto slot : artifact->artType->possibleSlots.at(target->bearerType()))
  1112. {
  1113. auto otherSlot = target->getSlot(slot);
  1114. if(otherSlot && otherSlot->artifact) //we need to exchange artifact for better one
  1115. {
  1116. ArtifactLocation destLocation(target, slot);
  1117. //if that artifact is better than what we have, pick it
  1118. if(compareArtifacts(artifact, otherSlot->artifact) && artifact->canBePutAt(destLocation, true)) //combined artifacts are not always allowed to move
  1119. {
  1120. cb->swapArtifacts(location, ArtifactLocation(target, target->getArtPos(otherSlot->artifact)));
  1121. changeMade = true;
  1122. break;
  1123. }
  1124. }
  1125. }
  1126. }
  1127. if(changeMade)
  1128. break; //start evaluating artifacts from scratch
  1129. }
  1130. }
  1131. while(changeMade);
  1132. };
  1133. equipBest(h, other, true);
  1134. if(other)
  1135. equipBest(h, other, false);
  1136. }
  1137. void VCAI::recruitCreatures(const CGDwelling * d, const CArmedInstance * recruiter)
  1138. {
  1139. //now used only for visited dwellings / towns, not BuyArmy goal
  1140. for(int i = 0; i < d->creatures.size(); i++)
  1141. {
  1142. if(!d->creatures[i].second.size())
  1143. continue;
  1144. int count = d->creatures[i].first;
  1145. CreatureID creID = d->creatures[i].second.back();
  1146. vstd::amin(count, ah->freeResources() / VLC->creh->creatures[creID]->cost);
  1147. if(count > 0)
  1148. cb->recruitCreatures(d, recruiter, creID, count, i);
  1149. }
  1150. }
  1151. bool VCAI::isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, boost::optional<float> movementCostLimit)
  1152. {
  1153. int3 op = obj->visitablePos();
  1154. auto paths = ah->getPathsToTile(h, op);
  1155. for(const auto & path : paths)
  1156. {
  1157. if(movementCostLimit && movementCostLimit.get() < path.movementCost())
  1158. return false;
  1159. if(isGoodForVisit(obj, h, path))
  1160. return true;
  1161. }
  1162. return false;
  1163. }
  1164. bool VCAI::isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, const AIPath & path) const
  1165. {
  1166. const int3 pos = obj->visitablePos();
  1167. const int3 targetPos = path.firstTileToGet();
  1168. if (!targetPos.valid())
  1169. return false;
  1170. if (!isTileNotReserved(h.get(), targetPos))
  1171. return false;
  1172. if (obj->wasVisited(playerID))
  1173. return false;
  1174. if (cb->getPlayerRelations(playerID, obj->tempOwner) != PlayerRelations::ENEMIES && !isWeeklyRevisitable(obj))
  1175. return false; // Otherwise we flag or get weekly resources / creatures
  1176. if (!isSafeToVisit(h, pos))
  1177. return false;
  1178. if (!shouldVisit(h, obj))
  1179. return false;
  1180. if (vstd::contains(alreadyVisited, obj))
  1181. return false;
  1182. if (vstd::contains(reservedObjs, obj))
  1183. return false;
  1184. // TODO: looks extra if we already have AIPath
  1185. //if (!isAccessibleForHero(targetPos, h))
  1186. // return false;
  1187. const CGObjectInstance * topObj = cb->getVisitableObjs(obj->visitablePos()).back(); //it may be hero visiting this obj
  1188. //we don't try visiting object on which allied or owned hero stands
  1189. // -> it will just trigger exchange windows and AI will be confused that obj behind doesn't get visited
  1190. if (topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES)
  1191. return false;
  1192. else
  1193. return true; //all of the following is met
  1194. }
  1195. bool VCAI::isTileNotReserved(const CGHeroInstance * h, int3 t) const
  1196. {
  1197. if(t.valid())
  1198. {
  1199. auto obj = cb->getTopObj(t);
  1200. if(obj && vstd::contains(ai->reservedObjs, obj)
  1201. && vstd::contains(reservedHeroesMap, h)
  1202. && !vstd::contains(reservedHeroesMap.at(h), obj))
  1203. return false; //do not capture object reserved by another hero
  1204. else
  1205. return true;
  1206. }
  1207. else
  1208. {
  1209. return false;
  1210. }
  1211. }
  1212. bool VCAI::canRecruitAnyHero(const CGTownInstance * t) const
  1213. {
  1214. //TODO: make gathering gold, building tavern or conquering town (?) possible subgoals
  1215. if(!t)
  1216. t = findTownWithTavern();
  1217. if(!t)
  1218. return false;
  1219. if(cb->getResourceAmount(Res::GOLD) < GameConstants::HERO_GOLD_COST) //TODO: use ResourceManager
  1220. return false;
  1221. if(cb->getHeroesInfo().size() >= ALLOWED_ROAMING_HEROES)
  1222. return false;
  1223. if(!cb->getAvailableHeroes(t).size())
  1224. return false;
  1225. return true;
  1226. }
  1227. void VCAI::wander(HeroPtr h)
  1228. {
  1229. auto visitTownIfAny = [this](HeroPtr h) -> bool
  1230. {
  1231. if (h->visitedTown)
  1232. {
  1233. townVisitsThisWeek[h].insert(h->visitedTown);
  1234. buildArmyIn(h->visitedTown);
  1235. return true;
  1236. }
  1237. return false;
  1238. };
  1239. //unclaim objects that are now dangerous for us
  1240. auto reservedObjsSetCopy = reservedHeroesMap[h];
  1241. for(auto obj : reservedObjsSetCopy)
  1242. {
  1243. if(!isSafeToVisit(h, obj->visitablePos()))
  1244. unreserveObject(h, obj);
  1245. }
  1246. TimeCheck tc("looking for wander destination");
  1247. while(h->movement)
  1248. {
  1249. validateVisitableObjs();
  1250. ah->updatePaths(h);
  1251. std::vector<ObjectIdRef> dests;
  1252. //also visit our reserved objects - but they are not prioritized to avoid running back and forth
  1253. vstd::copy_if(reservedHeroesMap[h], std::back_inserter(dests), [&](ObjectIdRef obj) -> bool
  1254. {
  1255. return ah->getPathsToTile(h, obj->visitablePos()).size();
  1256. });
  1257. int pass = 0;
  1258. std::vector<boost::optional<float>> distanceLimits =
  1259. {
  1260. 1.0,
  1261. 2.0,
  1262. boost::none
  1263. };
  1264. while(!dests.size() && pass < distanceLimits.size())
  1265. {
  1266. auto & distanceLimit = distanceLimits[pass];
  1267. logAi->debug("Looking for wander destination pass=%i, cost limit=%f", pass, distanceLimit.get_value_or(-1.0));
  1268. vstd::copy_if(visitableObjs, std::back_inserter(dests), [&](ObjectIdRef obj) -> bool
  1269. {
  1270. return isGoodForVisit(obj, h, distanceLimit);
  1271. });
  1272. pass++;
  1273. }
  1274. if(!dests.size())
  1275. {
  1276. logAi->debug("Looking for town destination");
  1277. if(cb->getVisitableObjs(h->visitablePos()).size() > 1)
  1278. moveHeroToTile(h->visitablePos(), h); //just in case we're standing on blocked subterranean gate
  1279. auto compareReinforcements = [h](const CGTownInstance * lhs, const CGTownInstance * rhs) -> bool
  1280. {
  1281. const CGHeroInstance * hptr = h.get();
  1282. auto r1 = howManyReinforcementsCanGet(hptr, lhs),
  1283. r2 = howManyReinforcementsCanGet(hptr, rhs);
  1284. if (r1 != r2)
  1285. return r1 < r2;
  1286. else
  1287. return howManyReinforcementsCanBuy(hptr, lhs) < howManyReinforcementsCanBuy(hptr, rhs);
  1288. };
  1289. std::vector<const CGTownInstance *> townsReachable;
  1290. std::vector<const CGTownInstance *> townsNotReachable;
  1291. for(const CGTownInstance * t : cb->getTownsInfo())
  1292. {
  1293. if(!t->visitingHero && !vstd::contains(townVisitsThisWeek[h], t))
  1294. {
  1295. if(isAccessibleForHero(t->visitablePos(), h))
  1296. townsReachable.push_back(t);
  1297. else
  1298. townsNotReachable.push_back(t);
  1299. }
  1300. }
  1301. if(townsReachable.size()) //travel to town with largest garrison, or empty - better than nothing
  1302. {
  1303. dests.push_back(*boost::max_element(townsReachable, compareReinforcements));
  1304. }
  1305. else if(townsNotReachable.size())
  1306. {
  1307. //TODO pick the truly best
  1308. const CGTownInstance * t = *boost::max_element(townsNotReachable, compareReinforcements);
  1309. logAi->debug("%s can't reach any town, we'll try to make our way to %s at %s", h->name, t->name, t->visitablePos().toString());
  1310. int3 pos1 = h->pos;
  1311. striveToGoal(sptr(Goals::ClearWayTo(t->visitablePos()).sethero(h))); //TODO: drop "strive", add to mainLoop
  1312. //if out hero is stuck, we may need to request another hero to clear the way we see
  1313. if(pos1 == h->pos && h == primaryHero()) //hero can't move
  1314. {
  1315. if(canRecruitAnyHero(t))
  1316. recruitHero(t);
  1317. }
  1318. break;
  1319. }
  1320. else if(cb->getResourceAmount(Res::GOLD) >= GameConstants::HERO_GOLD_COST)
  1321. {
  1322. std::vector<const CGTownInstance *> towns = cb->getTownsInfo();
  1323. vstd::erase_if(towns, [](const CGTownInstance * t) -> bool
  1324. {
  1325. for(const CGHeroInstance * h : cb->getHeroesInfo())
  1326. {
  1327. if(!t->getArmyStrength() || howManyReinforcementsCanGet(h, t))
  1328. return true;
  1329. }
  1330. return false;
  1331. });
  1332. if (towns.size())
  1333. {
  1334. recruitHero(*boost::max_element(towns, compareArmyStrength));
  1335. }
  1336. break;
  1337. }
  1338. else
  1339. {
  1340. logAi->debug("Nowhere more to go...");
  1341. break;
  1342. }
  1343. }
  1344. //end of objs empty
  1345. if(dests.size()) //performance improvement
  1346. {
  1347. Goals::TGoalVec targetObjectGoals;
  1348. for(auto destination : dests)
  1349. {
  1350. vstd::concatenate(targetObjectGoals, ah->howToVisitObj(h, destination, false));
  1351. }
  1352. if(targetObjectGoals.size())
  1353. {
  1354. auto bestObjectGoal = fh->chooseSolution(targetObjectGoals);
  1355. //wander should not cause heroes to be reserved - they are always considered free
  1356. if(bestObjectGoal->goalType == Goals::VISIT_OBJ)
  1357. {
  1358. auto chosenObject = cb->getObjInstance(ObjectInstanceID(bestObjectGoal->objid));
  1359. if(chosenObject != nullptr)
  1360. logAi->debug("Of all %d destinations, object %s at pos=%s seems nice", dests.size(), chosenObject->getObjectName(), chosenObject->pos.toString());
  1361. }
  1362. else
  1363. logAi->debug("Trying to realize goal of type %s as part of wandering.", bestObjectGoal->name());
  1364. try
  1365. {
  1366. decomposeGoal(bestObjectGoal)->accept(this);
  1367. }
  1368. catch(const goalFulfilledException & e)
  1369. {
  1370. if(e.goal->goalType == Goals::EGoals::VISIT_TILE || e.goal->goalType == Goals::EGoals::VISIT_OBJ)
  1371. continue;
  1372. throw e;
  1373. }
  1374. }
  1375. else
  1376. {
  1377. logAi->debug("Nowhere more to go...");
  1378. break;
  1379. }
  1380. visitTownIfAny(h);
  1381. }
  1382. }
  1383. visitTownIfAny(h); //in case hero is just sitting in town
  1384. }
  1385. void VCAI::setGoal(HeroPtr h, Goals::TSubgoal goal)
  1386. {
  1387. if(goal->invalid())
  1388. {
  1389. vstd::erase_if_present(lockedHeroes, h);
  1390. }
  1391. else
  1392. {
  1393. lockedHeroes[h] = goal;
  1394. goal->setisElementar(false); //Force always evaluate goals before realizing
  1395. }
  1396. }
  1397. void VCAI::evaluateGoal(HeroPtr h)
  1398. {
  1399. if(vstd::contains(lockedHeroes, h))
  1400. fh->setPriority(lockedHeroes[h]);
  1401. }
  1402. void VCAI::completeGoal(Goals::TSubgoal goal)
  1403. {
  1404. if (goal->goalType == Goals::WIN) //we can never complete this goal - unless we already won
  1405. return;
  1406. logAi->debug("Completing goal: %s", goal->name());
  1407. //notify Managers
  1408. ah->notifyGoalCompleted(goal);
  1409. //notify mainLoop()
  1410. goalsToRemove.push_back(goal); //will be removed from mainLoop() goals
  1411. for (auto basicGoal : basicGoals) //we could luckily fulfill any of our goals
  1412. {
  1413. if (basicGoal->fulfillsMe(goal))
  1414. goalsToRemove.push_back(basicGoal);
  1415. }
  1416. //unreserve heroes
  1417. if(const CGHeroInstance * h = goal->hero.get(true))
  1418. {
  1419. auto it = lockedHeroes.find(h);
  1420. if(it != lockedHeroes.end())
  1421. {
  1422. if(it->second == goal || it->second->fulfillsMe(goal)) //FIXME this is overspecified, fulfillsMe shoudl be complete
  1423. {
  1424. logAi->debug(goal->completeMessage());
  1425. lockedHeroes.erase(it); //goal fulfilled, free hero
  1426. }
  1427. }
  1428. }
  1429. else //complete goal for all heroes maybe?
  1430. {
  1431. vstd::erase_if(lockedHeroes, [goal](std::pair<HeroPtr, Goals::TSubgoal> p)
  1432. {
  1433. if(p.second == goal || p.second->fulfillsMe(goal)) //we could have fulfilled goals of other heroes by chance
  1434. {
  1435. logAi->debug(p.second->completeMessage());
  1436. return true;
  1437. }
  1438. return false;
  1439. });
  1440. }
  1441. }
  1442. void VCAI::battleStart(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool side)
  1443. {
  1444. NET_EVENT_HANDLER;
  1445. assert(playerID > PlayerColor::PLAYER_LIMIT || status.getBattle() == UPCOMING_BATTLE);
  1446. status.setBattle(ONGOING_BATTLE);
  1447. const CGObjectInstance * presumedEnemy = vstd::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
  1448. battlename = boost::str(boost::format("Starting battle of %s attacking %s at %s") % (hero1 ? hero1->name : "a army") % (presumedEnemy ? presumedEnemy->getObjectName() : "unknown enemy") % tile.toString());
  1449. CAdventureAI::battleStart(army1, army2, tile, hero1, hero2, side);
  1450. }
  1451. void VCAI::battleEnd(const BattleResult * br)
  1452. {
  1453. NET_EVENT_HANDLER;
  1454. assert(status.getBattle() == ONGOING_BATTLE);
  1455. status.setBattle(ENDING_BATTLE);
  1456. bool won = br->winner == myCb->battleGetMySide();
  1457. logAi->debug("Player %d (%s): I %s the %s!", playerID, playerID.getStr(), (won ? "won" : "lost"), battlename);
  1458. battlename.clear();
  1459. CAdventureAI::battleEnd(br);
  1460. }
  1461. void VCAI::waitTillFree()
  1462. {
  1463. auto unlock = vstd::makeUnlockSharedGuard(CGameState::mutex);
  1464. status.waitTillFree();
  1465. }
  1466. void VCAI::markObjectVisited(const CGObjectInstance * obj)
  1467. {
  1468. if(!obj)
  1469. return;
  1470. if(dynamic_cast<const CGVisitableOPH *>(obj)) //we may want to visit it with another hero
  1471. return;
  1472. if(dynamic_cast<const CGBonusingObject *>(obj)) //or another time
  1473. return;
  1474. if(obj->ID == Obj::MONSTER)
  1475. return;
  1476. alreadyVisited.insert(obj);
  1477. }
  1478. void VCAI::reserveObject(HeroPtr h, const CGObjectInstance * obj)
  1479. {
  1480. reservedObjs.insert(obj);
  1481. reservedHeroesMap[h].insert(obj);
  1482. logAi->debug("reserved object id=%d; address=%p; name=%s", obj->id, obj, obj->getObjectName());
  1483. }
  1484. void VCAI::unreserveObject(HeroPtr h, const CGObjectInstance * obj)
  1485. {
  1486. vstd::erase_if_present(reservedObjs, obj); //unreserve objects
  1487. vstd::erase_if_present(reservedHeroesMap[h], obj);
  1488. }
  1489. void VCAI::markHeroUnableToExplore(HeroPtr h)
  1490. {
  1491. heroesUnableToExplore.insert(h);
  1492. }
  1493. void VCAI::markHeroAbleToExplore(HeroPtr h)
  1494. {
  1495. vstd::erase_if_present(heroesUnableToExplore, h);
  1496. }
  1497. bool VCAI::isAbleToExplore(HeroPtr h)
  1498. {
  1499. return !vstd::contains(heroesUnableToExplore, h);
  1500. }
  1501. void VCAI::clearPathsInfo()
  1502. {
  1503. heroesUnableToExplore.clear();
  1504. }
  1505. void VCAI::validateVisitableObjs()
  1506. {
  1507. std::string errorMsg;
  1508. auto shouldBeErased = [&](const CGObjectInstance * obj) -> bool
  1509. {
  1510. if(obj)
  1511. return !cb->getObj(obj->id, false); // no verbose output needed as we check object visibility
  1512. else
  1513. return true;
  1514. };
  1515. //errorMsg is captured by ref so lambda will take the new text
  1516. errorMsg = " shouldn't be on the visitable objects list!";
  1517. vstd::erase_if(visitableObjs, shouldBeErased);
  1518. //FIXME: how comes our own heroes become inaccessible?
  1519. vstd::erase_if(reservedHeroesMap, [](std::pair<HeroPtr, std::set<const CGObjectInstance *>> hp) -> bool
  1520. {
  1521. return !hp.first.get(true);
  1522. });
  1523. for(auto & p : reservedHeroesMap)
  1524. {
  1525. errorMsg = " shouldn't be on list for hero " + p.first->name + "!";
  1526. vstd::erase_if(p.second, shouldBeErased);
  1527. }
  1528. errorMsg = " shouldn't be on the reserved objs list!";
  1529. vstd::erase_if(reservedObjs, shouldBeErased);
  1530. //TODO overkill, hidden object should not be removed. However, we can't know if hidden object is erased from game.
  1531. errorMsg = " shouldn't be on the already visited objs list!";
  1532. vstd::erase_if(alreadyVisited, shouldBeErased);
  1533. }
  1534. void VCAI::retrieveVisitableObjs(std::vector<const CGObjectInstance *> & out, bool includeOwned) const
  1535. {
  1536. foreach_tile_pos([&](const int3 & pos)
  1537. {
  1538. for(const CGObjectInstance * obj : myCb->getVisitableObjs(pos, false))
  1539. {
  1540. if(includeOwned || obj->tempOwner != playerID)
  1541. out.push_back(obj);
  1542. }
  1543. });
  1544. }
  1545. void VCAI::retrieveVisitableObjs()
  1546. {
  1547. foreach_tile_pos([&](const int3 & pos)
  1548. {
  1549. for(const CGObjectInstance * obj : myCb->getVisitableObjs(pos, false))
  1550. {
  1551. if(obj->tempOwner != playerID)
  1552. addVisitableObj(obj);
  1553. }
  1554. });
  1555. }
  1556. std::vector<const CGObjectInstance *> VCAI::getFlaggedObjects() const
  1557. {
  1558. std::vector<const CGObjectInstance *> ret;
  1559. for(const CGObjectInstance * obj : visitableObjs)
  1560. {
  1561. if(obj->tempOwner == playerID)
  1562. ret.push_back(obj);
  1563. }
  1564. return ret;
  1565. }
  1566. void VCAI::addVisitableObj(const CGObjectInstance * obj)
  1567. {
  1568. if(obj->ID == Obj::EVENT)
  1569. return;
  1570. visitableObjs.insert(obj);
  1571. // All teleport objects seen automatically assigned to appropriate channels
  1572. auto teleportObj = dynamic_cast<const CGTeleport *>(obj);
  1573. if(teleportObj)
  1574. CGTeleport::addToChannel(knownTeleportChannels, teleportObj);
  1575. }
  1576. const CGObjectInstance * VCAI::lookForArt(int aid) const
  1577. {
  1578. for(const CGObjectInstance * obj : ai->visitableObjs)
  1579. {
  1580. if(obj->ID == Obj::ARTIFACT && obj->subID == aid)
  1581. return obj;
  1582. }
  1583. return nullptr;
  1584. //TODO what if more than one artifact is available? return them all or some slection criteria
  1585. }
  1586. bool VCAI::isAccessible(const int3 & pos) const
  1587. {
  1588. //TODO precalculate for speed
  1589. for(const CGHeroInstance * h : cb->getHeroesInfo())
  1590. {
  1591. if(isAccessibleForHero(pos, h))
  1592. return true;
  1593. }
  1594. return false;
  1595. }
  1596. HeroPtr VCAI::getHeroWithGrail() const
  1597. {
  1598. for(const CGHeroInstance * h : cb->getHeroesInfo())
  1599. {
  1600. if(h->hasArt(2)) //grail
  1601. return h;
  1602. }
  1603. return nullptr;
  1604. }
  1605. const CGObjectInstance * VCAI::getUnvisitedObj(const std::function<bool(const CGObjectInstance *)> & predicate)
  1606. {
  1607. //TODO smarter definition of unvisited
  1608. for(const CGObjectInstance * obj : visitableObjs)
  1609. {
  1610. if(predicate(obj) && !vstd::contains(alreadyVisited, obj))
  1611. return obj;
  1612. }
  1613. return nullptr;
  1614. }
  1615. bool VCAI::isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies) const
  1616. {
  1617. // Don't visit tile occupied by allied hero
  1618. if(!includeAllies)
  1619. {
  1620. for(auto obj : cb->getVisitableObjs(pos))
  1621. {
  1622. if(obj->ID == Obj::HERO && cb->getPlayerRelations(ai->playerID, obj->tempOwner) != PlayerRelations::ENEMIES)
  1623. {
  1624. if(obj != h.get())
  1625. return false;
  1626. }
  1627. }
  1628. }
  1629. return cb->getPathsInfo(h.get())->getPathInfo(pos)->reachable();
  1630. }
  1631. bool VCAI::moveHeroToTile(int3 dst, HeroPtr h)
  1632. {
  1633. //TODO: consider if blockVisit objects change something in our checks: AIUtility::isBlockVisitObj()
  1634. auto afterMovementCheck = [&]() -> void
  1635. {
  1636. waitTillFree(); //movement may cause battle or blocking dialog
  1637. if(!h)
  1638. {
  1639. lostHero(h);
  1640. teleportChannelProbingList.clear();
  1641. if(status.channelProbing()) // if hero lost during channel probing we need to switch this mode off
  1642. status.setChannelProbing(false);
  1643. throw cannotFulfillGoalException("Hero was lost!");
  1644. }
  1645. };
  1646. logAi->debug("Moving hero %s to tile %s", h->name, dst.toString());
  1647. int3 startHpos = h->visitablePos();
  1648. bool ret = false;
  1649. if(startHpos == dst)
  1650. {
  1651. //FIXME: this assertion fails also if AI moves onto defeated guarded object
  1652. assert(cb->getVisitableObjs(dst).size() > 1); //there's no point in revisiting tile where there is no visitable object
  1653. cb->moveHero(*h, CGHeroInstance::convertPosition(dst, true));
  1654. afterMovementCheck(); // TODO: is it feasible to hero get killed there if game work properly?
  1655. // not sure if AI can currently reconsider to attack bank while staying on it. Check issue 2084 on mantis for more information.
  1656. ret = true;
  1657. }
  1658. else
  1659. {
  1660. CGPath path;
  1661. cb->getPathsInfo(h.get())->getPath(path, dst);
  1662. if(path.nodes.empty())
  1663. {
  1664. logAi->error("Hero %s cannot reach %s.", h->name, dst.toString());
  1665. throw goalFulfilledException(sptr(Goals::VisitTile(dst).sethero(h)));
  1666. }
  1667. int i = path.nodes.size() - 1;
  1668. auto getObj = [&](int3 coord, bool ignoreHero)
  1669. {
  1670. auto tile = cb->getTile(coord, false);
  1671. assert(tile);
  1672. return tile->topVisitableObj(ignoreHero);
  1673. //return cb->getTile(coord,false)->topVisitableObj(ignoreHero);
  1674. };
  1675. auto isTeleportAction = [&](CGPathNode::ENodeAction action) -> bool
  1676. {
  1677. if(action != CGPathNode::TELEPORT_NORMAL && action != CGPathNode::TELEPORT_BLOCKING_VISIT)
  1678. {
  1679. if(action != CGPathNode::TELEPORT_BATTLE)
  1680. {
  1681. return false;
  1682. }
  1683. }
  1684. return true;
  1685. };
  1686. auto getDestTeleportObj = [&](const CGObjectInstance * currentObject, const CGObjectInstance * nextObjectTop, const CGObjectInstance * nextObject) -> const CGObjectInstance *
  1687. {
  1688. if(CGTeleport::isConnected(currentObject, nextObjectTop))
  1689. return nextObjectTop;
  1690. if(nextObjectTop && nextObjectTop->ID == Obj::HERO)
  1691. {
  1692. if(CGTeleport::isConnected(currentObject, nextObject))
  1693. return nextObject;
  1694. }
  1695. return nullptr;
  1696. };
  1697. auto doMovement = [&](int3 dst, bool transit)
  1698. {
  1699. cb->moveHero(*h, CGHeroInstance::convertPosition(dst, true), transit);
  1700. };
  1701. auto doTeleportMovement = [&](ObjectInstanceID exitId, int3 exitPos)
  1702. {
  1703. destinationTeleport = exitId;
  1704. if(exitPos.valid())
  1705. destinationTeleportPos = CGHeroInstance::convertPosition(exitPos, true);
  1706. cb->moveHero(*h, h->pos);
  1707. destinationTeleport = ObjectInstanceID();
  1708. destinationTeleportPos = int3(-1);
  1709. afterMovementCheck();
  1710. };
  1711. auto doChannelProbing = [&]() -> void
  1712. {
  1713. auto currentPos = CGHeroInstance::convertPosition(h->pos, false);
  1714. auto currentExit = getObj(currentPos, true)->id;
  1715. status.setChannelProbing(true);
  1716. for(auto exit : teleportChannelProbingList)
  1717. doTeleportMovement(exit, int3(-1));
  1718. teleportChannelProbingList.clear();
  1719. status.setChannelProbing(false);
  1720. doTeleportMovement(currentExit, currentPos);
  1721. };
  1722. for(; i > 0; i--)
  1723. {
  1724. int3 currentCoord = path.nodes[i].coord;
  1725. int3 nextCoord = path.nodes[i - 1].coord;
  1726. auto currentObject = getObj(currentCoord, currentCoord == CGHeroInstance::convertPosition(h->pos, false));
  1727. auto nextObjectTop = getObj(nextCoord, false);
  1728. auto nextObject = getObj(nextCoord, true);
  1729. auto destTeleportObj = getDestTeleportObj(currentObject, nextObjectTop, nextObject);
  1730. if(isTeleportAction(path.nodes[i - 1].action) && destTeleportObj != nullptr)
  1731. {
  1732. //we use special login if hero standing on teleporter it's mean we need
  1733. doTeleportMovement(destTeleportObj->id, nextCoord);
  1734. if(teleportChannelProbingList.size())
  1735. doChannelProbing();
  1736. markObjectVisited(destTeleportObj); //FIXME: Monoliths are not correctly visited
  1737. continue;
  1738. }
  1739. //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  1740. if(path.nodes[i - 1].turns)
  1741. {
  1742. //blockedHeroes.insert(h); //to avoid attempts of moving heroes with very little MPs
  1743. break;
  1744. }
  1745. int3 endpos = path.nodes[i - 1].coord;
  1746. if(endpos == h->visitablePos())
  1747. continue;
  1748. bool isConnected = false;
  1749. bool isNextObjectTeleport = false;
  1750. // Check there is node after next one; otherwise transit is pointless
  1751. if(i - 2 >= 0)
  1752. {
  1753. isConnected = CGTeleport::isConnected(nextObjectTop, getObj(path.nodes[i - 2].coord, false));
  1754. isNextObjectTeleport = CGTeleport::isTeleport(nextObjectTop);
  1755. }
  1756. if(isConnected || isNextObjectTeleport)
  1757. {
  1758. // Hero should be able to go through object if it's allow transit
  1759. doMovement(endpos, true);
  1760. }
  1761. else if(path.nodes[i - 1].layer == EPathfindingLayer::AIR)
  1762. {
  1763. doMovement(endpos, true);
  1764. }
  1765. else
  1766. {
  1767. doMovement(endpos, false);
  1768. }
  1769. afterMovementCheck();
  1770. if(teleportChannelProbingList.size())
  1771. doChannelProbing();
  1772. }
  1773. if(path.nodes[0].action == CGPathNode::BLOCKING_VISIT)
  1774. {
  1775. ret = h && i == 0; // when we take resource we do not reach its position. We even might not move
  1776. }
  1777. }
  1778. if(h)
  1779. {
  1780. if(auto visitedObject = vstd::frontOrNull(cb->getVisitableObjs(h->visitablePos()))) //we stand on something interesting
  1781. {
  1782. if(visitedObject != *h)
  1783. performObjectInteraction(visitedObject, h);
  1784. }
  1785. }
  1786. if(h) //we could have lost hero after last move
  1787. {
  1788. completeGoal(sptr(Goals::VisitTile(dst).sethero(h))); //we stepped on some tile, anyway
  1789. completeGoal(sptr(Goals::ClearWayTo(dst).sethero(h)));
  1790. ret = ret || (dst == h->visitablePos());
  1791. if(!ret) //reserve object we are heading towards
  1792. {
  1793. auto obj = vstd::frontOrNull(cb->getVisitableObjs(dst));
  1794. if(obj && obj != *h)
  1795. reserveObject(h, obj);
  1796. }
  1797. if(startHpos == h->visitablePos() && !ret) //we didn't move and didn't reach the target
  1798. {
  1799. vstd::erase_if_present(lockedHeroes, h); //hero seemingly is confused or has only 95mp which is not enough to move
  1800. invalidPathHeroes.insert(h);
  1801. throw cannotFulfillGoalException("Invalid path found!");
  1802. }
  1803. evaluateGoal(h); //new hero position means new game situation
  1804. logAi->debug("Hero %s moved from %s to %s. Returning %d.", h->name, startHpos.toString(), h->visitablePos().toString(), ret);
  1805. }
  1806. return ret;
  1807. }
  1808. void VCAI::buildStructure(const CGTownInstance * t, BuildingID building)
  1809. {
  1810. auto name = t->town->buildings.at(building)->Name();
  1811. logAi->debug("Player %d will build %s in town of %s at %s", ai->playerID, name, t->name, t->pos.toString());
  1812. cb->buildBuilding(t, building); //just do this;
  1813. }
  1814. void VCAI::tryRealize(Goals::Explore & g)
  1815. {
  1816. throw cannotFulfillGoalException("EXPLORE is not an elementar goal!");
  1817. }
  1818. void VCAI::tryRealize(Goals::RecruitHero & g)
  1819. {
  1820. if(const CGTownInstance * t = findTownWithTavern())
  1821. {
  1822. recruitHero(t, true);
  1823. //TODO try to free way to blocked town
  1824. //TODO: adventure map tavern or prison?
  1825. }
  1826. else
  1827. {
  1828. throw cannotFulfillGoalException("No town to recruit hero!");
  1829. }
  1830. }
  1831. void VCAI::tryRealize(Goals::VisitTile & g)
  1832. {
  1833. if(!g.hero->movement)
  1834. throw cannotFulfillGoalException("Cannot visit tile: hero is out of MPs!");
  1835. if(g.tile == g.hero->visitablePos() && cb->getVisitableObjs(g.hero->visitablePos()).size() < 2)
  1836. {
  1837. logAi->warn("Why do I want to move hero %s to tile %s? Already standing on that tile! ", g.hero->name, g.tile.toString());
  1838. throw goalFulfilledException(sptr(g));
  1839. }
  1840. if(ai->moveHeroToTile(g.tile, g.hero.get()))
  1841. {
  1842. throw goalFulfilledException(sptr(g));
  1843. }
  1844. }
  1845. void VCAI::tryRealize(Goals::VisitObj & g)
  1846. {
  1847. auto position = g.tile;
  1848. if(!g.hero->movement)
  1849. throw cannotFulfillGoalException("Cannot visit object: hero is out of MPs!");
  1850. if(position == g.hero->visitablePos() && cb->getVisitableObjs(g.hero->visitablePos()).size() < 2)
  1851. {
  1852. logAi->warn("Why do I want to move hero %s to tile %s? Already standing on that tile! ", g.hero->name, g.tile.toString());
  1853. throw goalFulfilledException(sptr(g));
  1854. }
  1855. if(ai->moveHeroToTile(position, g.hero.get()))
  1856. {
  1857. throw goalFulfilledException(sptr(g));
  1858. }
  1859. }
  1860. void VCAI::tryRealize(Goals::VisitHero & g)
  1861. {
  1862. if(!g.hero->movement)
  1863. throw cannotFulfillGoalException("Cannot visit target hero: hero is out of MPs!");
  1864. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(g.objid));
  1865. if(obj)
  1866. {
  1867. if(ai->moveHeroToTile(obj->visitablePos(), g.hero.get()))
  1868. {
  1869. throw goalFulfilledException(sptr(g));
  1870. }
  1871. }
  1872. else
  1873. {
  1874. throw cannotFulfillGoalException("Cannot visit hero: object not found!");
  1875. }
  1876. }
  1877. void VCAI::tryRealize(Goals::BuildThis & g)
  1878. {
  1879. auto b = BuildingID(g.bid);
  1880. auto t = g.town;
  1881. if (t)
  1882. {
  1883. if (cb->canBuildStructure(t, b) == EBuildingState::ALLOWED)
  1884. {
  1885. logAi->debug("Player %d will build %s in town of %s at %s",
  1886. playerID, t->town->buildings.at(b)->Name(), t->name, t->pos.toString());
  1887. cb->buildBuilding(t, b);
  1888. throw goalFulfilledException(sptr(g));
  1889. }
  1890. }
  1891. throw cannotFulfillGoalException("Cannot build a given structure!");
  1892. }
  1893. void VCAI::tryRealize(Goals::DigAtTile & g)
  1894. {
  1895. assert(g.hero->visitablePos() == g.tile); //surely we want to crash here?
  1896. if(g.hero->diggingStatus() == EDiggingStatus::CAN_DIG)
  1897. {
  1898. cb->dig(g.hero.get());
  1899. completeGoal(sptr(g)); // finished digging
  1900. }
  1901. else
  1902. {
  1903. ai->lockedHeroes[g.hero] = sptr(g); //hero who tries to dig shouldn't do anything else
  1904. throw cannotFulfillGoalException("A hero can't dig!\n");
  1905. }
  1906. }
  1907. void VCAI::tryRealize(Goals::Trade & g) //trade
  1908. {
  1909. if(ah->freeResources()[g.resID] >= g.value) //goal is already fulfilled. Why we need this check, anyway?
  1910. throw goalFulfilledException(sptr(g));
  1911. int accquiredResources = 0;
  1912. if(const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(g.objid), false))
  1913. {
  1914. if(const IMarket * m = IMarket::castFrom(obj, false))
  1915. {
  1916. auto freeRes = ah->freeResources(); //trade only resources which are not reserved
  1917. for(auto it = Res::ResourceSet::nziterator(freeRes); it.valid(); it++)
  1918. {
  1919. auto res = it->resType;
  1920. if(res == g.resID) //sell any other resource
  1921. continue;
  1922. int toGive, toGet;
  1923. m->getOffer(res, g.resID, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  1924. toGive = toGive * (it->resVal / toGive); //round down
  1925. //TODO trade only as much as needed
  1926. if (toGive) //don't try to sell 0 resources
  1927. {
  1928. cb->trade(obj, EMarketMode::RESOURCE_RESOURCE, res, g.resID, toGive);
  1929. accquiredResources = toGet * (it->resVal / toGive);
  1930. logAi->debug("Traded %d of %s for %d of %s at %s", toGive, res, accquiredResources, g.resID, obj->getObjectName());
  1931. }
  1932. if (ah->freeResources()[g.resID] >= g.value)
  1933. throw goalFulfilledException(sptr(g)); //we traded all we needed
  1934. }
  1935. throw cannotFulfillGoalException("I cannot get needed resources by trade!");
  1936. }
  1937. else
  1938. {
  1939. throw cannotFulfillGoalException("I don't know how to use this object to raise resources!");
  1940. }
  1941. }
  1942. else
  1943. {
  1944. throw cannotFulfillGoalException("No object that could be used to raise resources!");
  1945. }
  1946. }
  1947. void VCAI::tryRealize(Goals::BuyArmy & g)
  1948. {
  1949. auto t = g.town;
  1950. ui64 valueBought = 0;
  1951. //buy the stacks with largest AI value
  1952. makePossibleUpgrades(t);
  1953. while (valueBought < g.value)
  1954. {
  1955. auto res = ah->allResources();
  1956. std::vector<creInfo> creaturesInDwellings;
  1957. for (int i = 0; i < t->creatures.size(); i++)
  1958. {
  1959. auto ci = infoFromDC(t->creatures[i]);
  1960. if(!ci.count
  1961. || ci.creID == -1
  1962. || (g.objid != -1 && ci.creID != g.objid)
  1963. || t->getUpperArmy()->getSlotFor(ci.creID) == SlotID())
  1964. continue;
  1965. vstd::amin(ci.count, res / ci.cre->cost); //max count we can afford
  1966. if(!ci.count)
  1967. continue;
  1968. ci.level = i; //this is important for Dungeon Summoning Portal
  1969. creaturesInDwellings.push_back(ci);
  1970. }
  1971. if (creaturesInDwellings.empty())
  1972. throw cannotFulfillGoalException("Can't buy any more creatures!");
  1973. creInfo ci =
  1974. *boost::max_element(creaturesInDwellings, [](const creInfo & lhs, const creInfo & rhs)
  1975. {
  1976. //max value of creatures we can buy with our res
  1977. int value1 = lhs.cre->AIValue * lhs.count,
  1978. value2 = rhs.cre->AIValue * rhs.count;
  1979. return value1 < value2;
  1980. });
  1981. cb->recruitCreatures(t, t->getUpperArmy(), ci.creID, ci.count, ci.level);
  1982. valueBought += ci.count * ci.cre->AIValue;
  1983. }
  1984. throw goalFulfilledException(sptr(g)); //we bought as many creatures as we wanted
  1985. }
  1986. void VCAI::tryRealize(Goals::Invalid & g)
  1987. {
  1988. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1989. }
  1990. void VCAI::tryRealize(Goals::AbstractGoal & g)
  1991. {
  1992. logAi->debug("Attempting realizing goal with code %s", g.name());
  1993. throw cannotFulfillGoalException("Unknown type of goal !");
  1994. }
  1995. const CGTownInstance * VCAI::findTownWithTavern() const
  1996. {
  1997. for(const CGTownInstance * t : cb->getTownsInfo())
  1998. if(t->hasBuilt(BuildingID::TAVERN) && !t->visitingHero)
  1999. return t;
  2000. return nullptr;
  2001. }
  2002. Goals::TSubgoal VCAI::getGoal(HeroPtr h) const
  2003. {
  2004. auto it = lockedHeroes.find(h);
  2005. if(it != lockedHeroes.end())
  2006. return it->second;
  2007. else
  2008. return sptr(Goals::Invalid());
  2009. }
  2010. std::vector<HeroPtr> VCAI::getUnblockedHeroes() const
  2011. {
  2012. std::vector<HeroPtr> ret;
  2013. for(auto h : cb->getHeroesInfo())
  2014. {
  2015. //&& !vstd::contains(lockedHeroes, h)
  2016. //at this point we assume heroes exhausted their locked goals
  2017. if(canAct(h))
  2018. ret.push_back(h);
  2019. }
  2020. return ret;
  2021. }
  2022. bool VCAI::canAct(HeroPtr h) const
  2023. {
  2024. auto mission = lockedHeroes.find(h);
  2025. if(mission != lockedHeroes.end())
  2026. {
  2027. //FIXME: I'm afraid there can be other conditions when heroes can act but not move :?
  2028. if(mission->second->goalType == Goals::DIG_AT_TILE && !mission->second->isElementar)
  2029. return false;
  2030. }
  2031. return h->movement;
  2032. }
  2033. HeroPtr VCAI::primaryHero() const
  2034. {
  2035. auto hs = cb->getHeroesInfo();
  2036. if (hs.empty())
  2037. return nullptr;
  2038. else
  2039. return *boost::max_element(hs, compareHeroStrength);
  2040. }
  2041. void VCAI::endTurn()
  2042. {
  2043. logAi->info("Player %d (%s) ends turn", playerID, playerID.getStr());
  2044. if(!status.haveTurn())
  2045. {
  2046. logAi->error("Not having turn at the end of turn???");
  2047. }
  2048. logAi->debug("Resources at the end of turn: %s", cb->getResourceAmount().toString());
  2049. do
  2050. {
  2051. cb->endTurn();
  2052. }
  2053. 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
  2054. logGlobal->info("Player %d (%s) ended turn", playerID, playerID.getStr());
  2055. }
  2056. void VCAI::striveToGoal(Goals::TSubgoal basicGoal)
  2057. {
  2058. //TODO: this function is deprecated and should be dropped altogether
  2059. auto goalToDecompose = basicGoal;
  2060. Goals::TSubgoal elementarGoal = sptr(Goals::Invalid());
  2061. int maxAbstractGoals = 10;
  2062. while (!elementarGoal->isElementar && maxAbstractGoals)
  2063. {
  2064. try
  2065. {
  2066. elementarGoal = decomposeGoal(goalToDecompose);
  2067. }
  2068. catch (goalFulfilledException & e)
  2069. {
  2070. //it is impossible to continue some goals (like exploration, for example)
  2071. completeGoal(e.goal); //put in goalsToRemove
  2072. logAi->debug("Goal %s decomposition failed: goal was completed as much as possible", e.goal->name());
  2073. return;
  2074. }
  2075. catch (std::exception & e)
  2076. {
  2077. goalsToRemove.push_back(basicGoal);
  2078. logAi->debug("Goal %s decomposition failed: %s", basicGoal->name(), e.what());
  2079. return;
  2080. }
  2081. if (elementarGoal->isAbstract) //we can decompose it further
  2082. {
  2083. goalsToAdd.push_back(elementarGoal);
  2084. //decompose further now - this is necesssary if we can't add over 10 goals in the pool
  2085. goalToDecompose = elementarGoal;
  2086. //there is a risk of infinite abstract goal loop, though it indicates failed logic
  2087. maxAbstractGoals--;
  2088. }
  2089. else if (elementarGoal->isElementar) //should be
  2090. {
  2091. logAi->debug("Found elementar goal %s", elementarGoal->name());
  2092. ultimateGoalsFromBasic[elementarGoal].push_back(goalToDecompose); //TODO: how about indirect basicGoal?
  2093. break;
  2094. }
  2095. else //should never be here
  2096. throw cannotFulfillGoalException("Goal %s is neither abstract nor elementar!" + basicGoal->name());
  2097. }
  2098. //realize best goal
  2099. if (!elementarGoal->invalid())
  2100. {
  2101. logAi->debug("Trying to realize %s (value %2.3f)", elementarGoal->name(), elementarGoal->priority);
  2102. try
  2103. {
  2104. boost::this_thread::interruption_point();
  2105. elementarGoal->accept(this); //visitor pattern
  2106. boost::this_thread::interruption_point();
  2107. }
  2108. catch (boost::thread_interrupted & e)
  2109. {
  2110. logAi->debug("Player %d: Making turn thread received an interruption!", playerID);
  2111. throw; //rethrow, we want to truly end this thread
  2112. }
  2113. catch (goalFulfilledException & e)
  2114. {
  2115. //the sub-goal was completed successfully
  2116. completeGoal(e.goal);
  2117. //local goal was also completed
  2118. completeGoal(elementarGoal);
  2119. }
  2120. catch (std::exception & e)
  2121. {
  2122. logAi->debug("Failed to realize subgoal of type %s, I will stop.", elementarGoal->name());
  2123. logAi->debug("The error message was: %s", e.what());
  2124. //erase base goal if we failed to execute decomposed goal
  2125. for (auto basicGoalToRemove : ultimateGoalsFromBasic[elementarGoal])
  2126. goalsToRemove.push_back(basicGoalToRemove);
  2127. }
  2128. }
  2129. }
  2130. Goals::TSubgoal VCAI::decomposeGoal(Goals::TSubgoal ultimateGoal)
  2131. {
  2132. if(ultimateGoal->isElementar)
  2133. {
  2134. logAi->warn("Trying to decompose elementar goal %s", ultimateGoal->name());
  2135. return ultimateGoal;
  2136. }
  2137. const int searchDepth = 30;
  2138. Goals::TSubgoal goal = ultimateGoal;
  2139. logAi->debug("Decomposing goal %s", ultimateGoal->name());
  2140. int maxGoals = searchDepth; //preventing deadlock for mutually dependent goals
  2141. while (maxGoals)
  2142. {
  2143. boost::this_thread::interruption_point();
  2144. goal = goal->whatToDoToAchieve(); //may throw if decomposition fails
  2145. --maxGoals;
  2146. if (goal == ultimateGoal) //compare objects by value
  2147. if (goal->isElementar == ultimateGoal->isElementar)
  2148. throw cannotFulfillGoalException((boost::format("Goal dependency loop detected for %s!")
  2149. % ultimateGoal->name()).str());
  2150. if (goal->isAbstract || goal->isElementar)
  2151. return goal;
  2152. else
  2153. logAi->debug("Considering: %s", goal->name());
  2154. }
  2155. throw cannotFulfillGoalException("Too many subgoals, don't know what to do");
  2156. }
  2157. void VCAI::performTypicalActions()
  2158. {
  2159. for(auto h : getUnblockedHeroes())
  2160. {
  2161. if(!h) //hero might be lost. getUnblockedHeroes() called once on start of turn
  2162. continue;
  2163. logAi->debug("Hero %s started wandering, MP=%d", h->name.c_str(), h->movement);
  2164. makePossibleUpgrades(*h);
  2165. pickBestArtifacts(*h);
  2166. try
  2167. {
  2168. wander(h);
  2169. }
  2170. catch(std::exception & e)
  2171. {
  2172. logAi->debug("Cannot use this hero anymore, received exception: %s", e.what());
  2173. continue;
  2174. }
  2175. }
  2176. }
  2177. void VCAI::buildArmyIn(const CGTownInstance * t)
  2178. {
  2179. makePossibleUpgrades(t->visitingHero);
  2180. makePossibleUpgrades(t);
  2181. recruitCreatures(t, t->getUpperArmy());
  2182. moveCreaturesToHero(t);
  2183. }
  2184. void VCAI::checkHeroArmy(HeroPtr h)
  2185. {
  2186. auto it = lockedHeroes.find(h);
  2187. if(it != lockedHeroes.end())
  2188. {
  2189. if(it->second->goalType == Goals::GATHER_ARMY && it->second->value <= h->getArmyStrength())
  2190. completeGoal(sptr(Goals::GatherArmy(it->second->value).sethero(h)));
  2191. }
  2192. }
  2193. void VCAI::recruitHero(const CGTownInstance * t, bool throwing)
  2194. {
  2195. logAi->debug("Trying to recruit a hero in %s at %s", t->name, t->visitablePos().toString());
  2196. auto heroes = cb->getAvailableHeroes(t);
  2197. if(heroes.size())
  2198. {
  2199. auto hero = heroes[0];
  2200. if(heroes.size() >= 2) //makes sense to recruit two heroes with starting amries in first week
  2201. {
  2202. if(heroes[1]->getTotalStrength() > hero->getTotalStrength())
  2203. hero = heroes[1];
  2204. }
  2205. cb->recruitHero(t, hero);
  2206. throw goalFulfilledException(sptr(Goals::RecruitHero().settown(t)));
  2207. }
  2208. else if(throwing)
  2209. {
  2210. throw cannotFulfillGoalException("No available heroes in tavern in " + t->nodeName());
  2211. }
  2212. }
  2213. void VCAI::finish()
  2214. {
  2215. if(makingTurn)
  2216. {
  2217. makingTurn->interrupt();
  2218. makingTurn->join();
  2219. makingTurn.reset();
  2220. }
  2221. }
  2222. void VCAI::requestActionASAP(std::function<void()> whatToDo)
  2223. {
  2224. boost::thread newThread([this, whatToDo]()
  2225. {
  2226. setThreadName("VCAI::requestActionASAP::whatToDo");
  2227. SET_GLOBAL_STATE(this);
  2228. boost::shared_lock<boost::shared_mutex> gsLock(CGameState::mutex);
  2229. whatToDo();
  2230. });
  2231. }
  2232. void VCAI::lostHero(HeroPtr h)
  2233. {
  2234. logAi->debug("I lost my hero %s. It's best to forget and move on.", h.name);
  2235. vstd::erase_if_present(lockedHeroes, h);
  2236. for(auto obj : reservedHeroesMap[h])
  2237. {
  2238. vstd::erase_if_present(reservedObjs, obj); //unreserve all objects for that hero
  2239. }
  2240. vstd::erase_if_present(reservedHeroesMap, h);
  2241. vstd::erase_if_present(visitedHeroes, h);
  2242. for (auto heroVec : visitedHeroes)
  2243. {
  2244. vstd::erase_if_present(heroVec.second, h);
  2245. }
  2246. //remove goals with removed hero assigned from main loop
  2247. vstd::erase_if(ultimateGoalsFromBasic, [&](const std::pair<Goals::TSubgoal, Goals::TGoalVec> & x) -> bool
  2248. {
  2249. if(x.first->hero == h)
  2250. return true;
  2251. else
  2252. return false;
  2253. });
  2254. auto removedHeroGoalPredicate = [&](const Goals::TSubgoal & x) ->bool
  2255. {
  2256. if(x->hero == h)
  2257. return true;
  2258. else
  2259. return false;
  2260. };
  2261. vstd::erase_if(basicGoals, removedHeroGoalPredicate);
  2262. vstd::erase_if(goalsToAdd, removedHeroGoalPredicate);
  2263. vstd::erase_if(goalsToRemove, removedHeroGoalPredicate);
  2264. for(auto goal : ultimateGoalsFromBasic)
  2265. vstd::erase_if(goal.second, removedHeroGoalPredicate);
  2266. }
  2267. void VCAI::answerQuery(QueryID queryID, int selection)
  2268. {
  2269. logAi->debug("I'll answer the query %d giving the choice %d", queryID, selection);
  2270. if(queryID != QueryID(-1))
  2271. {
  2272. cb->selectionMade(selection, queryID);
  2273. }
  2274. else
  2275. {
  2276. logAi->debug("Since the query ID is %d, the answer won't be sent. This is not a real query!", queryID);
  2277. //do nothing
  2278. }
  2279. }
  2280. void VCAI::requestSent(const CPackForServer * pack, int requestID)
  2281. {
  2282. //BNLOG("I have sent request of type %s", typeid(*pack).name());
  2283. if(auto reply = dynamic_cast<const QueryReply *>(pack))
  2284. {
  2285. status.attemptedAnsweringQuery(reply->qid, requestID);
  2286. }
  2287. }
  2288. std::string VCAI::getBattleAIName() const
  2289. {
  2290. if(settings["server"]["enemyAI"].getType() == JsonNode::JsonType::DATA_STRING)
  2291. return settings["server"]["enemyAI"].String();
  2292. else
  2293. return "BattleAI";
  2294. }
  2295. void VCAI::validateObject(const CGObjectInstance * obj)
  2296. {
  2297. validateObject(obj->id);
  2298. }
  2299. void VCAI::validateObject(ObjectIdRef obj)
  2300. {
  2301. auto matchesId = [&](const CGObjectInstance * hlpObj) -> bool
  2302. {
  2303. return hlpObj->id == obj.id;
  2304. };
  2305. if(!obj)
  2306. {
  2307. vstd::erase_if(visitableObjs, matchesId);
  2308. for(auto & p : reservedHeroesMap)
  2309. vstd::erase_if(p.second, matchesId);
  2310. vstd::erase_if(reservedObjs, matchesId);
  2311. }
  2312. }
  2313. AIStatus::AIStatus()
  2314. {
  2315. battle = NO_BATTLE;
  2316. havingTurn = false;
  2317. ongoingHeroMovement = false;
  2318. ongoingChannelProbing = false;
  2319. }
  2320. AIStatus::~AIStatus()
  2321. {
  2322. }
  2323. void AIStatus::setBattle(BattleState BS)
  2324. {
  2325. boost::unique_lock<boost::mutex> lock(mx);
  2326. LOG_TRACE_PARAMS(logAi, "battle state=%d", (int)BS);
  2327. battle = BS;
  2328. cv.notify_all();
  2329. }
  2330. BattleState AIStatus::getBattle()
  2331. {
  2332. boost::unique_lock<boost::mutex> lock(mx);
  2333. return battle;
  2334. }
  2335. void AIStatus::addQuery(QueryID ID, std::string description)
  2336. {
  2337. if(ID == QueryID(-1))
  2338. {
  2339. logAi->debug("The \"query\" has an id %d, it'll be ignored as non-query. Description: %s", ID, description);
  2340. return;
  2341. }
  2342. assert(ID.getNum() >= 0);
  2343. boost::unique_lock<boost::mutex> lock(mx);
  2344. assert(!vstd::contains(remainingQueries, ID));
  2345. remainingQueries[ID] = description;
  2346. cv.notify_all();
  2347. logAi->debug("Adding query %d - %s. Total queries count: %d", ID, description, remainingQueries.size());
  2348. }
  2349. void AIStatus::removeQuery(QueryID ID)
  2350. {
  2351. boost::unique_lock<boost::mutex> lock(mx);
  2352. assert(vstd::contains(remainingQueries, ID));
  2353. std::string description = remainingQueries[ID];
  2354. remainingQueries.erase(ID);
  2355. cv.notify_all();
  2356. logAi->debug("Removing query %d - %s. Total queries count: %d", ID, description, remainingQueries.size());
  2357. }
  2358. int AIStatus::getQueriesCount()
  2359. {
  2360. boost::unique_lock<boost::mutex> lock(mx);
  2361. return remainingQueries.size();
  2362. }
  2363. void AIStatus::startedTurn()
  2364. {
  2365. boost::unique_lock<boost::mutex> lock(mx);
  2366. havingTurn = true;
  2367. cv.notify_all();
  2368. }
  2369. void AIStatus::madeTurn()
  2370. {
  2371. boost::unique_lock<boost::mutex> lock(mx);
  2372. havingTurn = false;
  2373. cv.notify_all();
  2374. }
  2375. void AIStatus::waitTillFree()
  2376. {
  2377. boost::unique_lock<boost::mutex> lock(mx);
  2378. while(battle != NO_BATTLE || !remainingQueries.empty() || !objectsBeingVisited.empty() || ongoingHeroMovement)
  2379. cv.timed_wait(lock, boost::posix_time::milliseconds(100));
  2380. }
  2381. bool AIStatus::haveTurn()
  2382. {
  2383. boost::unique_lock<boost::mutex> lock(mx);
  2384. return havingTurn;
  2385. }
  2386. void AIStatus::attemptedAnsweringQuery(QueryID queryID, int answerRequestID)
  2387. {
  2388. boost::unique_lock<boost::mutex> lock(mx);
  2389. assert(vstd::contains(remainingQueries, queryID));
  2390. std::string description = remainingQueries[queryID];
  2391. logAi->debug("Attempted answering query %d - %s. Request id=%d. Waiting for results...", queryID, description, answerRequestID);
  2392. requestToQueryID[answerRequestID] = queryID;
  2393. }
  2394. void AIStatus::receivedAnswerConfirmation(int answerRequestID, int result)
  2395. {
  2396. assert(vstd::contains(requestToQueryID, answerRequestID));
  2397. QueryID query = requestToQueryID[answerRequestID];
  2398. assert(vstd::contains(remainingQueries, query));
  2399. requestToQueryID.erase(answerRequestID);
  2400. if(result)
  2401. {
  2402. removeQuery(query);
  2403. }
  2404. else
  2405. {
  2406. logAi->error("Something went really wrong, failed to answer query %d : %s", query.getNum(), remainingQueries[query]);
  2407. //TODO safely retry
  2408. }
  2409. }
  2410. void AIStatus::heroVisit(const CGObjectInstance * obj, bool started)
  2411. {
  2412. boost::unique_lock<boost::mutex> lock(mx);
  2413. if(started)
  2414. {
  2415. objectsBeingVisited.push_back(obj);
  2416. }
  2417. else
  2418. {
  2419. // There can be more than one object visited at the time (eg. hero visits Subterranean Gate
  2420. // causing visit to hero on the other side.
  2421. // However, we are guaranteed that start/end visit notification maintain stack order.
  2422. assert(!objectsBeingVisited.empty());
  2423. objectsBeingVisited.pop_back();
  2424. }
  2425. cv.notify_all();
  2426. }
  2427. void AIStatus::setMove(bool ongoing)
  2428. {
  2429. boost::unique_lock<boost::mutex> lock(mx);
  2430. ongoingHeroMovement = ongoing;
  2431. cv.notify_all();
  2432. }
  2433. void AIStatus::setChannelProbing(bool ongoing)
  2434. {
  2435. boost::unique_lock<boost::mutex> lock(mx);
  2436. ongoingChannelProbing = ongoing;
  2437. cv.notify_all();
  2438. }
  2439. bool AIStatus::channelProbing()
  2440. {
  2441. return ongoingChannelProbing;
  2442. }
  2443. bool isWeeklyRevisitable(const CGObjectInstance * obj)
  2444. {
  2445. //TODO: allow polling of remaining creatures in dwelling
  2446. if(dynamic_cast<const CGVisitableOPW *>(obj)) // ensures future compatibility, unlike IDs
  2447. return true;
  2448. if(dynamic_cast<const CGDwelling *>(obj))
  2449. return true;
  2450. if(dynamic_cast<const CBank *>(obj)) //banks tend to respawn often in mods
  2451. return true;
  2452. switch(obj->ID)
  2453. {
  2454. case Obj::STABLES:
  2455. case Obj::MAGIC_WELL:
  2456. case Obj::HILL_FORT:
  2457. return true;
  2458. case Obj::BORDER_GATE:
  2459. case Obj::BORDERGUARD:
  2460. return (dynamic_cast<const CGKeys *>(obj))->wasMyColorVisited(ai->playerID); //FIXME: they could be revisited sooner than in a week
  2461. }
  2462. return false;
  2463. }
  2464. bool shouldVisit(HeroPtr h, const CGObjectInstance * obj)
  2465. {
  2466. switch(obj->ID)
  2467. {
  2468. case Obj::TOWN:
  2469. case Obj::HERO: //never visit our heroes at random
  2470. return obj->tempOwner != h->tempOwner; //do not visit our towns at random
  2471. case Obj::BORDER_GATE:
  2472. {
  2473. for(auto q : ai->myCb->getMyQuests())
  2474. {
  2475. if(q.obj == obj)
  2476. {
  2477. return false; // do not visit guards or gates when wandering
  2478. }
  2479. }
  2480. return true; //we don't have this quest yet
  2481. }
  2482. case Obj::BORDERGUARD: //open borderguard if possible
  2483. return (dynamic_cast<const CGKeys *>(obj))->wasMyColorVisited(ai->playerID);
  2484. case Obj::SEER_HUT:
  2485. case Obj::QUEST_GUARD:
  2486. {
  2487. for(auto q : ai->myCb->getMyQuests())
  2488. {
  2489. if(q.obj == obj)
  2490. {
  2491. if(q.quest->checkQuest(h.h))
  2492. return true; //we completed the quest
  2493. else
  2494. return false; //we can't complete this quest
  2495. }
  2496. }
  2497. return true; //we don't have this quest yet
  2498. }
  2499. case Obj::CREATURE_GENERATOR1:
  2500. {
  2501. if(obj->tempOwner != h->tempOwner)
  2502. return true; //flag just in case
  2503. bool canRecruitCreatures = false;
  2504. const CGDwelling * d = dynamic_cast<const CGDwelling *>(obj);
  2505. for(auto level : d->creatures)
  2506. {
  2507. for(auto c : level.second)
  2508. {
  2509. if(h->getSlotFor(CreatureID(c)) != SlotID())
  2510. canRecruitCreatures = true;
  2511. }
  2512. }
  2513. return canRecruitCreatures;
  2514. }
  2515. case Obj::HILL_FORT:
  2516. {
  2517. for(auto slot : h->Slots())
  2518. {
  2519. if(slot.second->type->upgrades.size())
  2520. return true; //TODO: check price?
  2521. }
  2522. return false;
  2523. }
  2524. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  2525. case Obj::MONOLITH_ONE_WAY_EXIT:
  2526. case Obj::MONOLITH_TWO_WAY:
  2527. case Obj::WHIRLPOOL:
  2528. return false;
  2529. case Obj::SCHOOL_OF_MAGIC:
  2530. case Obj::SCHOOL_OF_WAR:
  2531. {
  2532. if (ai->ah->freeGold() < 1000)
  2533. return false;
  2534. break;
  2535. }
  2536. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2537. if(h->level < 12)
  2538. return false;
  2539. break;
  2540. case Obj::TREE_OF_KNOWLEDGE:
  2541. {
  2542. TResources myRes = ai->ah->freeResources();
  2543. if(myRes[Res::GOLD] < 2000 || myRes[Res::GEMS] < 10)
  2544. return false;
  2545. break;
  2546. }
  2547. case Obj::MAGIC_WELL:
  2548. return h->mana < h->manaLimit();
  2549. case Obj::PRISON:
  2550. return ai->myCb->getHeroesInfo().size() < VLC->modh->settings.MAX_HEROES_ON_MAP_PER_PLAYER;
  2551. case Obj::TAVERN:
  2552. {
  2553. //TODO: make AI actually recruit heroes
  2554. //TODO: only on request
  2555. if(ai->myCb->getHeroesInfo().size() >= VLC->modh->settings.MAX_HEROES_ON_MAP_PER_PLAYER)
  2556. return false;
  2557. else if(ai->ah->freeGold() < GameConstants::HERO_GOLD_COST)
  2558. return false;
  2559. break;
  2560. }
  2561. case Obj::BOAT:
  2562. return false;
  2563. //Boats are handled by pathfinder
  2564. case Obj::EYE_OF_MAGI:
  2565. return false; //this object is useless to visit, but could be visited indefinitely
  2566. }
  2567. if(obj->wasVisited(*h)) //it must pointer to hero instance, heroPtr calls function wasVisited(ui8 player);
  2568. return false;
  2569. return true;
  2570. }