VCAI.cpp 82 KB

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