VCAI.cpp 84 KB

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