VCAI.cpp 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482
  1. #include "StdInc.h"
  2. #include "VCAI.h"
  3. #define I_AM_ELEMENTAR return CGoal(*this).setisElementar(true)
  4. const int ACTUAL_RESOURCE_COUNT = 7;
  5. const double SAFE_ATTACK_CONSTANT = 2.5;
  6. using namespace vstd;
  7. //one thread may be turn of AI and another will be handling a side effect for AI2
  8. boost::thread_specific_ptr<CCallback> cb;
  9. boost::thread_specific_ptr<VCAI> ai;
  10. // CCallback *cb;
  11. // VCAI *ai;
  12. //helper RAII to manage global ai/cb ptrs
  13. struct SetGlobalState
  14. {
  15. SetGlobalState(VCAI * AI)
  16. {
  17. assert(!ai.get());
  18. assert(!cb.get());
  19. ai.reset(AI);
  20. cb.reset(AI->myCb);
  21. }
  22. ~SetGlobalState()
  23. {
  24. ai.release();
  25. cb.release();
  26. }
  27. };
  28. #define SET_GLOBAL_STATE(ai) SetGlobalState _hlpSetState(ai);
  29. #define NET_EVENT_HANDLER SET_GLOBAL_STATE(this)
  30. #define MAKING_TURN SET_GLOBAL_STATE(this)
  31. 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)
  32. const int HERO_GOLD_COST = 2500;
  33. const int ALLOWED_ROAMING_HEROES = 8;
  34. const int GOLD_MINE_PRODUCTION = 1000, WOOD_ORE_MINE_PRODUCTION = 2, RESOURCE_MINE_PRODUCTION = 1;
  35. bool compareHeroStrength(const CGHeroInstance *h1, const CGHeroInstance *h2)
  36. {
  37. return h1->getTotalStrength() < h2->getTotalStrength();
  38. }
  39. bool compareArmyStrength(const CArmedInstance *a1, const CArmedInstance *a2)
  40. {
  41. return a1->getArmyStrength() < a2->getArmyStrength();
  42. }
  43. //TODO integrate with that constants file
  44. namespace Obj
  45. {
  46. enum
  47. {
  48. BOAT = 8,
  49. CREATURE_BANK = 16,
  50. CREATURE_GENERATOR1 = 17,
  51. DERELICT_SHIP = 24,
  52. GARRISON = 33,
  53. MONOLITH1 = 43,
  54. MONOLITH2 = 44,
  55. MONOLITH3 = 45,
  56. MINE = 53,
  57. MONSTER = 54,
  58. OBELISK = 57,
  59. CRYPT = 84,
  60. SHIPWRECK = 85,
  61. TRADING_POST = 99,
  62. SUBTERRANEAN_GATE = 103,
  63. WHIRLPOOL = 111,
  64. BORDER_GATE = 212,
  65. GARRISON2 = 219,
  66. };
  67. }
  68. static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  69. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  70. struct AILogger
  71. {
  72. AILogger()
  73. {
  74. lvl = 0;
  75. }
  76. int lvl;
  77. struct Tab
  78. {
  79. Tab()
  80. {
  81. logger.lvl++;
  82. }
  83. ~Tab()
  84. {
  85. logger.lvl--;
  86. }
  87. };
  88. } logger;
  89. struct TimeCheck
  90. {
  91. CStopWatch time;
  92. std::string txt;
  93. TimeCheck(crstring TXT) : txt(TXT)
  94. {
  95. }
  96. ~TimeCheck()
  97. {
  98. BNLOG("Time of %s was %d ms.", txt % time.getDiff());
  99. }
  100. };
  101. template<typename T>
  102. void removeDuplicates(std::vector<T> &vec)
  103. {
  104. boost::sort(vec);
  105. vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
  106. }
  107. template<typename Range, typename Predicate>
  108. void erase_if(Range &vec, Predicate pred)
  109. {
  110. vec.erase(boost::remove_if(vec, pred),vec.end());
  111. }
  112. struct AtScopeExit
  113. {
  114. boost::function<void()> foo;
  115. AtScopeExit(const boost::function<void()> &FOO) : foo(FOO)
  116. {}
  117. ~AtScopeExit()
  118. {
  119. foo();
  120. }
  121. };
  122. void foreach_tile_pos(boost::function<void(const int3& pos)> foo)
  123. {
  124. for(int i = 0; i < cb->getMapSize().x; i++)
  125. for(int j = 0; j < cb->getMapSize().y; j++)
  126. for(int k = 0; k < cb->getMapSize().z; k++)
  127. foo(int3(i,j,k));
  128. }
  129. void foreach_neighbour(const int3 &pos, boost::function<void(const int3& pos)> foo)
  130. {
  131. BOOST_FOREACH(const int3 &dir, dirs)
  132. {
  133. const int3 n = pos + dir;
  134. if(cb->isInTheMap(n))
  135. foo(pos+dir);
  136. }
  137. }
  138. unsigned char &retreiveTileN(std::vector< std::vector< std::vector<unsigned char> > > &vectors, const int3 &pos)
  139. {
  140. return vectors[pos.x][pos.y][pos.z];
  141. }
  142. const unsigned char &retreiveTileN(const std::vector< std::vector< std::vector<unsigned char> > > &vectors, const int3 &pos)
  143. {
  144. return vectors[pos.x][pos.y][pos.z];
  145. }
  146. void foreach_tile(std::vector< std::vector< std::vector<unsigned char> > > &vectors, boost::function<void(unsigned char &in)> foo)
  147. {
  148. for(auto i = vectors.begin(); i != vectors.end(); i++)
  149. for(auto j = i->begin(); j != i->end(); j++)
  150. for(auto z = j->begin(); z != j->end(); z++)
  151. foo(*z);
  152. }
  153. struct ObjInfo
  154. {
  155. int3 pos;
  156. std::string name;
  157. ObjInfo(){}
  158. ObjInfo(const CGObjectInstance *obj)
  159. {
  160. pos = obj->pos;
  161. name = obj->getHoverText();
  162. }
  163. };
  164. std::map<const CGObjectInstance *, ObjInfo> helperObjInfo;
  165. template <typename Container, typename Item>
  166. bool remove_if_present(Container &c, const Item &item)
  167. {
  168. Container::iterator i = std::find(c.begin(), c.end(), item);
  169. if(i != c.end())
  170. {
  171. c.erase(i);
  172. return true;
  173. }
  174. return false;
  175. }
  176. template <typename Container, typename Pred>
  177. void erase(Container &c, Pred &pred)
  178. {
  179. c.erase(boost::remove_if(c, pred), c.end());
  180. }
  181. bool isReachable(const CGObjectInstance *obj)
  182. {
  183. return cb->getPathInfo(obj->visitablePos())->turns < 255;
  184. }
  185. ui64 howManyReinforcementsCanGet(const CGHeroInstance *h, const CGTownInstance *t)
  186. {
  187. ui64 ret = 0;
  188. int freeHeroSlots = GameConstants::ARMY_SIZE - h->stacksCount();
  189. std::vector<const CStackInstance *> toMove;
  190. BOOST_FOREACH(auto const slot, t->Slots())
  191. {
  192. //can be merged woth another stack?
  193. TSlot dst = h->getSlotFor(slot.second->getCreatureID());
  194. if(h->hasStackAtSlot(dst))
  195. ret += t->getPower(slot.first);
  196. else
  197. toMove.push_back(slot.second);
  198. }
  199. boost::sort(toMove, [](const CStackInstance *lhs, const CStackInstance *rhs)
  200. {
  201. return lhs->getPower() < rhs->getPower();
  202. });
  203. BOOST_REVERSE_FOREACH(const CStackInstance *stack, toMove)
  204. {
  205. if(freeHeroSlots)
  206. {
  207. ret += stack->getPower();
  208. freeHeroSlots--;
  209. }
  210. else
  211. break;
  212. }
  213. return ret;
  214. }
  215. std::string strFromInt3(int3 pos)
  216. {
  217. std::ostringstream oss;
  218. oss << pos;
  219. return oss.str();
  220. }
  221. bool isCloser(const CGObjectInstance *lhs, const CGObjectInstance *rhs)
  222. {
  223. const CGPathNode *ln = cb->getPathInfo(lhs->visitablePos()), *rn = cb->getPathInfo(rhs->visitablePos());
  224. if(ln->turns != rn->turns)
  225. return ln->turns < rn->turns;
  226. return (ln->moveRemains > rn->moveRemains);
  227. };
  228. ui64 evaluateDanger(const CGObjectInstance *obj);
  229. ui64 evaluateDanger(crint3 tile)
  230. {
  231. const TerrainTile *t = cb->getTile(tile, false);
  232. if(!t) //we can know about guard but can't check its tile (the edge of fow)
  233. return 190000000; //MUCH
  234. ui64 objectDanger = 0, guardDanger = 0;
  235. if(t->visitable)
  236. objectDanger = evaluateDanger(t->visitableObjects.front());
  237. int3 guardPos = cb->guardingCreaturePosition(tile);
  238. if(guardPos.x >= 0 && guardPos != tile)
  239. guardDanger = evaluateDanger(guardPos);
  240. //TODO mozna odwiedzic blockvis nie ruszajac straznika
  241. return std::max(objectDanger, guardDanger);
  242. return 0;
  243. }
  244. ui64 evaluateDanger(const CGObjectInstance *obj)
  245. {
  246. if(obj->tempOwner < GameConstants::PLAYER_LIMIT && cb->getPlayerRelations(obj->tempOwner, ai->playerID)) //owned or allied objects don't pose any threat
  247. return 0;
  248. switch(obj->ID)
  249. {
  250. case GameConstants::HEROI_TYPE:
  251. {
  252. InfoAboutHero iah;
  253. cb->getHeroInfo(obj, iah);
  254. return iah.army.getStrength();
  255. }
  256. case GameConstants::TOWNI_TYPE:
  257. case Obj::GARRISON: case Obj::GARRISON2: //garrison
  258. {
  259. InfoAboutTown iat;
  260. cb->getTownInfo(obj, iat);
  261. return iat.army.getStrength();
  262. }
  263. case GameConstants::CREI_TYPE:
  264. {
  265. //TODO!!!!!!!!
  266. const CGCreature *cre = dynamic_cast<const CGCreature*>(obj);
  267. return cre->getArmyStrength();
  268. }
  269. case Obj::CRYPT: //crypt
  270. {
  271. return VLC->creh->creatures[56]->AIValue * 25
  272. + VLC->creh->creatures[58]->AIValue * 20
  273. + VLC->creh->creatures[60]->AIValue * 9
  274. + VLC->creh->creatures[62]->AIValue * 5;
  275. }
  276. case Obj::CREATURE_BANK: //crebank
  277. case Obj::SHIPWRECK: //shipwreck
  278. case Obj::DERELICT_SHIP: //derelict ship
  279. //TODO estimate danger
  280. return 1000000000;
  281. case Obj::WHIRLPOOL: //whirlpool
  282. case Obj::MONOLITH1:
  283. case Obj::MONOLITH2:
  284. case Obj::MONOLITH3:
  285. //TODO mechinism for handling monoliths
  286. return 1000000000;
  287. default:
  288. return 0;
  289. }
  290. }
  291. bool compareDanger(const CGObjectInstance *lhs, const CGObjectInstance *rhs)
  292. {
  293. return evaluateDanger(lhs) < evaluateDanger(rhs);
  294. }
  295. VCAI::VCAI(void)
  296. {
  297. LOG_ENTRY;
  298. myCb = NULL;
  299. battleAIName = "StupidAI";
  300. makingTurn = NULL;
  301. }
  302. VCAI::~VCAI(void)
  303. {
  304. LOG_ENTRY;
  305. }
  306. void VCAI::availableCreaturesChanged(const CGDwelling *town)
  307. {
  308. NET_EVENT_HANDLER;
  309. LOG_ENTRY;
  310. }
  311. void VCAI::heroMoved(const TryMoveHero & details)
  312. {
  313. NET_EVENT_HANDLER;
  314. LOG_ENTRY;
  315. if(details.result == TryMoveHero::TELEPORTATION)
  316. {
  317. const TerrainTile *t1 = cb->getTile(CGHeroInstance::convertPosition(details.start, false)),
  318. *t2 = cb->getTile(CGHeroInstance::convertPosition(details.end, false));
  319. if(t1->visitable && t2->visitable)
  320. {
  321. const CGObjectInstance *o1 = t1->visitableObjects.front(),
  322. *o2 = t2->visitableObjects.front();
  323. if(o1->ID == Obj::SUBTERRANEAN_GATE && o2->ID == Obj::SUBTERRANEAN_GATE)
  324. {
  325. knownSubterraneanGates[o1] = o2;
  326. knownSubterraneanGates[o2] = o1;
  327. }
  328. }
  329. }
  330. }
  331. void VCAI::stackChagedCount(const StackLocation &location, const TQuantity &change, bool isAbsolute)
  332. {
  333. NET_EVENT_HANDLER;
  334. LOG_ENTRY;
  335. }
  336. void VCAI::heroInGarrisonChange(const CGTownInstance *town)
  337. {
  338. NET_EVENT_HANDLER;
  339. LOG_ENTRY;
  340. }
  341. void VCAI::centerView(int3 pos, int focusTime)
  342. {
  343. NET_EVENT_HANDLER;
  344. LOG_ENTRY;
  345. }
  346. void VCAI::artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst)
  347. {
  348. NET_EVENT_HANDLER;
  349. LOG_ENTRY;
  350. }
  351. void VCAI::artifactAssembled(const ArtifactLocation &al)
  352. {
  353. NET_EVENT_HANDLER;
  354. LOG_ENTRY;
  355. }
  356. void VCAI::showTavernWindow(const CGObjectInstance *townOrTavern)
  357. {
  358. NET_EVENT_HANDLER;
  359. LOG_ENTRY;
  360. }
  361. void VCAI::playerBlocked(int reason)
  362. {
  363. NET_EVENT_HANDLER;
  364. LOG_ENTRY;
  365. if (reason == PlayerBlocked::UPCOMING_BATTLE)
  366. status.setBattle(UPCOMING_BATTLE);
  367. }
  368. void VCAI::showPuzzleMap()
  369. {
  370. NET_EVENT_HANDLER;
  371. LOG_ENTRY;
  372. }
  373. void VCAI::showShipyardDialog(const IShipyard *obj)
  374. {
  375. NET_EVENT_HANDLER;
  376. LOG_ENTRY;
  377. }
  378. void VCAI::gameOver(ui8 player, bool victory)
  379. {
  380. NET_EVENT_HANDLER;
  381. LOG_ENTRY;
  382. BNLOG("Player %d: I heard that player %d %s.", playerID % (int)player % (victory ? "won" : "lost"));
  383. if(player == playerID)
  384. {
  385. if(victory)
  386. {
  387. tlog0 << "VCAI: I won! Incredible!\n";
  388. tlog0 << "Turn nr " << myCb->getDate() << std::endl;
  389. }
  390. else
  391. {
  392. tlog0 << "VCAI: Player " << (int)player << " lost. It's me. What a disappointment! :(\n";
  393. }
  394. //let's make Impossible difficulty finally standing to its name :>
  395. if(myCb->getStartInfo()->difficulty == 4 && !victory)
  396. {
  397. //play dirty: crash the whole engine to avoid lose
  398. //that way AI is unbeatable!
  399. *(int*)NULL = 666;
  400. }
  401. if(makingTurn)
  402. makingTurn->interrupt();
  403. }
  404. }
  405. void VCAI::artifactPut(const ArtifactLocation &al)
  406. {
  407. NET_EVENT_HANDLER;
  408. LOG_ENTRY;
  409. }
  410. void VCAI::artifactRemoved(const ArtifactLocation &al)
  411. {
  412. NET_EVENT_HANDLER;
  413. LOG_ENTRY;
  414. }
  415. void VCAI::stacksErased(const StackLocation &location)
  416. {
  417. NET_EVENT_HANDLER;
  418. LOG_ENTRY;
  419. }
  420. void VCAI::artifactDisassembled(const ArtifactLocation &al)
  421. {
  422. NET_EVENT_HANDLER;
  423. LOG_ENTRY;
  424. }
  425. void VCAI::heroVisit(const CGHeroInstance *visitor, const CGObjectInstance *visitedObj, bool start)
  426. {
  427. NET_EVENT_HANDLER;
  428. LOG_ENTRY;
  429. if(start && visitedObj->ID != Obj::MONSTER)
  430. alreadyVisited.push_back(visitedObj);
  431. }
  432. void VCAI::availableArtifactsChanged(const CGBlackMarket *bm /*= NULL*/)
  433. {
  434. NET_EVENT_HANDLER;
  435. LOG_ENTRY;
  436. }
  437. void VCAI::heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town)
  438. {
  439. NET_EVENT_HANDLER;
  440. LOG_ENTRY;
  441. //buildArmyIn(town);
  442. //moveCreaturesToHero(town);
  443. }
  444. void VCAI::tileHidden(const boost::unordered_set<int3, ShashInt3> &pos)
  445. {
  446. NET_EVENT_HANDLER;
  447. LOG_ENTRY;
  448. // BOOST_FOREACH(int3 tile, pos)
  449. // BOOST_FOREACH(const CGObjectInstance *obj, cb->getVisitableObjs(tile))
  450. // remove_if_present(visitableObjs, obj);
  451. visitableObjs.erase(boost::remove_if(visitableObjs, [&](const CGObjectInstance *obj){return !myCb->getObj(obj->id);}), visitableObjs.end());
  452. }
  453. void VCAI::tileRevealed(const boost::unordered_set<int3, ShashInt3> &pos)
  454. {
  455. NET_EVENT_HANDLER;
  456. LOG_ENTRY;
  457. BOOST_FOREACH(int3 tile, pos)
  458. BOOST_FOREACH(const CGObjectInstance *obj, myCb->getVisitableObjs(tile))
  459. addVisitableObj(obj);
  460. }
  461. void VCAI::heroExchangeStarted(si32 hero1, si32 hero2)
  462. {
  463. NET_EVENT_HANDLER;
  464. LOG_ENTRY;
  465. }
  466. void VCAI::heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val)
  467. {
  468. NET_EVENT_HANDLER;
  469. LOG_ENTRY;
  470. }
  471. void VCAI::showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level)
  472. {
  473. NET_EVENT_HANDLER;
  474. LOG_ENTRY;
  475. }
  476. void VCAI::heroMovePointsChanged(const CGHeroInstance * hero)
  477. {
  478. NET_EVENT_HANDLER;
  479. LOG_ENTRY;
  480. }
  481. void VCAI::stackChangedType(const StackLocation &location, const CCreature &newType)
  482. {
  483. NET_EVENT_HANDLER;
  484. LOG_ENTRY;
  485. }
  486. void VCAI::stacksRebalanced(const StackLocation &src, const StackLocation &dst, TQuantity count)
  487. {
  488. NET_EVENT_HANDLER;
  489. LOG_ENTRY;
  490. }
  491. void VCAI::newObject(const CGObjectInstance * obj)
  492. {
  493. NET_EVENT_HANDLER;
  494. LOG_ENTRY;
  495. if(obj->isVisitable())
  496. addVisitableObj(obj);
  497. }
  498. void VCAI::objectRemoved(const CGObjectInstance *obj)
  499. {
  500. NET_EVENT_HANDLER;
  501. LOG_ENTRY;
  502. if(remove_if_present(visitableObjs, obj))
  503. assert(obj->isVisitable());
  504. }
  505. void VCAI::showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor)
  506. {
  507. NET_EVENT_HANDLER;
  508. LOG_ENTRY;
  509. }
  510. void VCAI::playerBonusChanged(const Bonus &bonus, bool gain)
  511. {
  512. NET_EVENT_HANDLER;
  513. LOG_ENTRY;
  514. }
  515. void VCAI::newStackInserted(const StackLocation &location, const CStackInstance &stack)
  516. {
  517. NET_EVENT_HANDLER;
  518. LOG_ENTRY;
  519. }
  520. void VCAI::heroCreated(const CGHeroInstance*)
  521. {
  522. NET_EVENT_HANDLER;
  523. LOG_ENTRY;
  524. }
  525. void VCAI::advmapSpellCast(const CGHeroInstance * caster, int spellID)
  526. {
  527. NET_EVENT_HANDLER;
  528. LOG_ENTRY;
  529. }
  530. void VCAI::showInfoDialog(const std::string &text, const std::vector<Component*> &components, int soundID)
  531. {
  532. NET_EVENT_HANDLER;
  533. LOG_ENTRY;
  534. }
  535. void VCAI::requestRealized(PackageApplied *pa)
  536. {
  537. NET_EVENT_HANDLER;
  538. LOG_ENTRY;
  539. if(status.haveTurn())
  540. {
  541. if(pa->packType == typeList.getTypeID<EndTurn>())
  542. if(pa->result)
  543. status.madeTurn();
  544. }
  545. if(pa->packType == typeList.getTypeID<QueryReply>())
  546. {
  547. status.removeQuery();
  548. }
  549. }
  550. void VCAI::receivedResource(int type, int val)
  551. {
  552. NET_EVENT_HANDLER;
  553. LOG_ENTRY;
  554. }
  555. void VCAI::stacksSwapped(const StackLocation &loc1, const StackLocation &loc2)
  556. {
  557. NET_EVENT_HANDLER;
  558. LOG_ENTRY;
  559. }
  560. void VCAI::showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor)
  561. {
  562. NET_EVENT_HANDLER;
  563. LOG_ENTRY;
  564. }
  565. void VCAI::heroManaPointsChanged(const CGHeroInstance * hero)
  566. {
  567. NET_EVENT_HANDLER;
  568. LOG_ENTRY;
  569. }
  570. void VCAI::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  571. {
  572. NET_EVENT_HANDLER;
  573. LOG_ENTRY;
  574. }
  575. void VCAI::battleResultsApplied()
  576. {
  577. NET_EVENT_HANDLER;
  578. LOG_ENTRY;
  579. assert(status.getBattle() == ENDING_BATTLE);
  580. status.setBattle(NO_BATTLE);
  581. }
  582. void VCAI::objectPropertyChanged(const SetObjectProperty * sop)
  583. {
  584. NET_EVENT_HANDLER;
  585. LOG_ENTRY;
  586. if(sop->what == ObjProperty::OWNER)
  587. {
  588. if(sop->val == playerID)
  589. remove_if_present(visitableObjs, myCb->getObj(sop->id));
  590. //TODO restore lost obj
  591. }
  592. }
  593. void VCAI::buildChanged(const CGTownInstance *town, int buildingID, int what)
  594. {
  595. NET_EVENT_HANDLER;
  596. LOG_ENTRY;
  597. }
  598. void VCAI::heroBonusChanged(const CGHeroInstance *hero, const Bonus &bonus, bool gain)
  599. {
  600. NET_EVENT_HANDLER;
  601. LOG_ENTRY;
  602. }
  603. void VCAI::showMarketWindow(const IMarket *market, const CGHeroInstance *visitor)
  604. {
  605. NET_EVENT_HANDLER;
  606. LOG_ENTRY;
  607. }
  608. void VCAI::init(CCallback * CB)
  609. {
  610. myCb = CB;
  611. cbc = CB;
  612. NET_EVENT_HANDLER;
  613. LOG_ENTRY;
  614. playerID = myCb->getMyColor();
  615. myCb->waitTillRealize = true;
  616. retreiveVisitableObjs(visitableObjs);
  617. }
  618. void VCAI::yourTurn()
  619. {
  620. NET_EVENT_HANDLER;
  621. LOG_ENTRY;
  622. status.startedTurn();
  623. makingTurn = new boost::thread(&VCAI::makeTurn, this);
  624. }
  625. void VCAI::heroGotLevel(const CGHeroInstance *hero, int pskill, std::vector<ui16> &skills, boost::function<void(ui32)> &callback)
  626. {
  627. NET_EVENT_HANDLER;
  628. LOG_ENTRY;
  629. status.addQuery();
  630. callback(0);
  631. }
  632. void VCAI::showBlockingDialog(const std::string &text, const std::vector<Component> &components, ui32 askID, const int soundID, bool selection, bool cancel)
  633. {
  634. NET_EVENT_HANDLER;
  635. LOG_ENTRY;
  636. int sel = 0;
  637. status.addQuery();
  638. if(selection) //select from multiple components -> take the last one (they're indexed [1-size])
  639. sel = components.size();
  640. if(!selection && cancel) //yes&no -> always answer yes, we are a brave AI :)
  641. sel = 1;
  642. cb->selectionMade(sel, askID);
  643. }
  644. void VCAI::showGarrisonDialog(const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, boost::function<void()> &onEnd)
  645. {
  646. NET_EVENT_HANDLER;
  647. LOG_ENTRY;
  648. status.addQuery();
  649. onEnd();
  650. }
  651. void VCAI::serialize(COSer<CSaveFile> &h, const int version)
  652. {
  653. NET_EVENT_HANDLER;
  654. LOG_ENTRY;
  655. }
  656. void VCAI::serialize(CISer<CLoadFile> &h, const int version)
  657. {
  658. NET_EVENT_HANDLER;
  659. LOG_ENTRY;
  660. }
  661. void makePossibleUpgrades(const CArmedInstance *obj)
  662. {
  663. if(!obj)
  664. return;
  665. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  666. {
  667. if(const CStackInstance *s = obj->getStackPtr(i))
  668. {
  669. UpgradeInfo ui;
  670. cb->getUpgradeInfo(obj, i, ui);
  671. if(ui.oldID >= 0 && cb->getResourceAmount().canAfford(ui.cost[0] * s->count))
  672. {
  673. cb->upgradeCreature(obj, i, ui.newID[0]);
  674. }
  675. }
  676. }
  677. }
  678. void VCAI::makeTurn()
  679. {
  680. MAKING_TURN;
  681. boost::shared_lock<boost::shared_mutex> gsLock(cb->getGsMutex());
  682. setThreadName(-1, "VCAI::makeTurn");
  683. BNLOG("Player %d starting turn", playerID);
  684. INDENT;
  685. if(cb->getDate(1) == 1)
  686. {
  687. townVisitsThisWeek.clear();
  688. std::vector<const CGObjectInstance *> objs;
  689. retreiveVisitableObjs(objs, true);
  690. BOOST_FOREACH(const CGObjectInstance *obj, objs)
  691. {
  692. if(obj->ID == Obj::CREATURE_GENERATOR1 && !vstd::contains(visitableObjs, obj))
  693. visitableObjs.push_back(obj);
  694. }
  695. }
  696. if(cb->getSelectedHero())
  697. cb->recalculatePaths();
  698. makeTurnInternal();
  699. vstd::clear_pointer(makingTurn);
  700. return;
  701. }
  702. void VCAI::makeTurnInternal()
  703. {
  704. blockedHeroes.clear();
  705. saving = 0;
  706. try
  707. {
  708. striveToGoal(CGoal(WIN));
  709. striveToGoal(CGoal(BUILD));
  710. striveToGoal(CGoal(EXPLORE)); //if we have any MPs left, why not use them?
  711. }
  712. catch(boost::thread_interrupted &e)
  713. {
  714. tlog0 << "Making turn thread has been interrupted. We'll end without calling endTurn.\n";
  715. return;
  716. }
  717. catch(std::exception &e)
  718. {
  719. tlog0 << "Making turn thread has caught an exception: " << e.what() << "\n";
  720. }
  721. endTurn();
  722. }
  723. bool VCAI::goVisitObj(const CGObjectInstance * obj, const CGHeroInstance * h)
  724. {
  725. int3 dst = obj->visitablePos();
  726. BNLOG("%s will try to visit %s at (%s)", h->name % obj->hoverName % strFromInt3(dst));
  727. return moveHeroToTile(dst, h);
  728. }
  729. void VCAI::moveCreaturesToHero(const CGTownInstance * t)
  730. {
  731. if(t->visitingHero)
  732. {
  733. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  734. {
  735. if(const CStackInstance *s = t->getStackPtr(i))
  736. {
  737. //find d
  738. int dstSlot = t->visitingHero->getSlotFor(s->type);
  739. if(dstSlot >= 0)
  740. {
  741. if(t->visitingHero->hasStackAtSlot(dstSlot))
  742. cb->mergeStacks(t, t->visitingHero, i, dstSlot);
  743. else
  744. cb->swapCreatures(t, t->visitingHero, i, dstSlot);
  745. }
  746. }
  747. }
  748. }
  749. }
  750. void VCAI::recruitCreatures(const CGTownInstance * t)
  751. {
  752. for(int i = 0; i < t->creatures.size(); i++)
  753. {
  754. if(!t->creatures[i].second.size())
  755. continue;
  756. int count = t->creatures[i].first;
  757. int creID = t->creatures[i].second.back();
  758. const CCreature *c = VLC->creh->creatures[creID];
  759. // if(containsSavedRes(c->cost))
  760. // continue;
  761. TResources myRes = cb->getResourceAmount();
  762. myRes[Res::GOLD] -= GOLD_RESERVE;
  763. amin(count, myRes / VLC->creh->creatures[creID]->cost);
  764. if(count > 0)
  765. cb->recruitCreatures(t, creID, count, i);
  766. }
  767. }
  768. void VCAI::buildStructure(const CGTownInstance * t)
  769. {
  770. //TODO make *real* town development system
  771. const int buildings[] = {5, 11, 14, 16, 0, 12, 7, 8, 9, 13, 30, 31, 32, 33, 34, 35, 36, 37, 38,
  772. 39, 40, 41, 42, 43, 1, 2, 3, 4, 17, 18, 19, 21, 22, 23};
  773. for(int i = 0; i < ARRAY_COUNT(buildings); i++)
  774. {
  775. if(t->hasBuilt(buildings[i]))
  776. continue;
  777. const CBuilding *b = VLC->buildh->buildings[t->subID][buildings[i]];
  778. int canBuild = cb->canBuildStructure(t, buildings[i]);
  779. if(canBuild == EBuildingState::ALLOWED)
  780. {
  781. if(!containsSavedRes(b->resources))
  782. {
  783. BNLOG("Player %d will build %s in town of %s at %s", playerID % b->Name() % t->name % t->pos);
  784. cb->buildBuilding(t, buildings[i]);
  785. }
  786. break;
  787. }
  788. else if(canBuild == EBuildingState::NO_RESOURCES)
  789. {
  790. TResources mine = cb->getResourceAmount(), cost = VLC->buildh->buildings[t->subID][buildings[i]]->resources,
  791. income = estimateIncome();
  792. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  793. {
  794. int diff = mine[i] - cost[i] + income[i];
  795. if(diff < 0)
  796. saving[i] = 1;
  797. }
  798. continue;
  799. }
  800. }
  801. }
  802. bool isSafeToVisit(const CGHeroInstance *h, crint3 tile)
  803. {
  804. const ui64 heroStrength = h->getTotalStrength(),
  805. dangerStrength = evaluateDanger(tile);
  806. if(dangerStrength)
  807. {
  808. if(heroStrength / SAFE_ATTACK_CONSTANT > dangerStrength)
  809. {
  810. BNLOG("It's, safe for %s to visit tile %s", h->name % tile);
  811. return true;
  812. }
  813. else
  814. return false;
  815. }
  816. return true; //there's no danger
  817. }
  818. std::vector<const CGObjectInstance *> VCAI::getPossibleDestinations(const CGHeroInstance *h)
  819. {
  820. validateVisitableObjs();
  821. std::vector<const CGObjectInstance *> possibleDestinations;
  822. BOOST_FOREACH(const CGObjectInstance *obj, visitableObjs)
  823. if(cb->getPathInfo(obj->visitablePos())->reachable() && obj->tempOwner != playerID)
  824. possibleDestinations.push_back(obj);
  825. boost::sort(possibleDestinations, isCloser);
  826. possibleDestinations.erase(boost::remove_if(possibleDestinations, [&](const CGObjectInstance *obj) -> bool
  827. {
  828. if(vstd::contains(alreadyVisited, obj))
  829. return true;
  830. if(!isSafeToVisit(h, obj->visitablePos()))
  831. return true;
  832. return false;
  833. }),possibleDestinations.end());
  834. return possibleDestinations;
  835. }
  836. void VCAI::wander(const CGHeroInstance * h)
  837. {
  838. while(1)
  839. {
  840. auto dests = getPossibleDestinations(h);
  841. if(!dests.size())
  842. {
  843. auto compareReinforcements = [h](const CGTownInstance *lhs, const CGTownInstance *rhs) -> bool
  844. {
  845. return howManyReinforcementsCanGet(h, lhs) < howManyReinforcementsCanGet(h, rhs);
  846. };
  847. std::vector<const CGTownInstance *> townsReachable;
  848. std::vector<const CGTownInstance *> townsNotReachable;
  849. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  850. {
  851. if(!t->visitingHero && howManyReinforcementsCanGet(h,t) && !vstd::contains(townVisitsThisWeek[h], t))
  852. {
  853. if(isReachable(t))
  854. townsReachable.push_back(t);
  855. else
  856. townsNotReachable.push_back(t);
  857. }
  858. }
  859. // towns.erase(boost::remove_if(towns, [=](const CGTownInstance *t) -> bool
  860. // {
  861. // return !!t->visitingHero || !isReachable(t) || !howManyReinforcementsCanGet(h,t) || vstd::contains(townVisitsThisWeek[h], t);
  862. // }),towns.end());
  863. if(townsReachable.size())
  864. {
  865. boost::sort(townsReachable, compareReinforcements);
  866. dests.push_back(townsReachable.back());
  867. }
  868. else if(townsNotReachable.size())
  869. {
  870. boost::sort(townsNotReachable, compareReinforcements);
  871. //TODO pick the truly best
  872. const CGTownInstance *t = townsNotReachable.back();
  873. BNLOG("%s can't reach any town, we'll try to make our way to %s at %s", h->name % t->name % t->visitablePos());
  874. int3 pos1 = h->pos;
  875. striveToGoal(CGoal(CLEAR_WAY_TO).settile(t->visitablePos()).sethero(h));
  876. if(pos1 == h->pos && h == primaryHero()) //hero can't move
  877. {
  878. /*boost::sort(unreachableTowns, compareArmyStrength);*/
  879. //BOOST_FOREACH(const CGTownInstance *t, unreachableTowns)
  880. if(cb->getResourceAmount(Res::GOLD) >= HERO_GOLD_COST && cb->getHeroesInfo().size() < ALLOWED_ROAMING_HEROES && cb->getAvailableHeroes(t).size())
  881. recruitHero(t);
  882. }
  883. break;
  884. }
  885. else if(cb->getResourceAmount(Res::GOLD) >= HERO_GOLD_COST)
  886. {
  887. std::vector<const CGTownInstance *> towns = cb->getTownsInfo();
  888. erase_if(towns, [](const CGTownInstance *t) -> bool
  889. {
  890. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  891. if(!t->getArmyStrength() || howManyReinforcementsCanGet(h, t))
  892. return true;
  893. return false;
  894. });
  895. boost::sort(towns, compareArmyStrength);
  896. if(towns.size())
  897. recruitHero(towns.back());
  898. break;
  899. }
  900. else
  901. {
  902. PNLOG("Nowhere more to go...\n");
  903. break;
  904. }
  905. }
  906. if(!goVisitObj(dests.front(), h))
  907. {
  908. BNLOG("Hero %s apparently used all MPs (%d left)\n", h->name % h->movement);
  909. break;
  910. }
  911. //TODO real solution for moving army
  912. if(h->visitedTown)
  913. {
  914. townVisitsThisWeek[h].push_back(h->visitedTown);
  915. buildArmyIn(h->visitedTown);
  916. break;
  917. }
  918. }
  919. }
  920. void VCAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side)
  921. {
  922. assert(playerID > GameConstants::PLAYER_LIMIT || status.getBattle() == UPCOMING_BATTLE);
  923. status.setBattle(ONGOING_BATTLE);
  924. const TerrainTile *t = myCb->getTile(tile); //may be NULL in some very are cases -> eg. visited monolith and fighting with an enemy at the FoW covered exit
  925. battlename = boost::str(boost::format("battle of %s attacking %s at %s") % (hero1 ? hero1->name : "a army") % (t ? t->visitableObjects.back()->hoverName : "unknown enemy") % tile);
  926. CAdventureAI::battleStart(army1, army2, tile, hero1, hero2, side);
  927. }
  928. void VCAI::battleEnd(const BattleResult *br)
  929. {
  930. assert(status.getBattle() == ONGOING_BATTLE);
  931. status.setBattle(ENDING_BATTLE);
  932. bool won = br->winner == myCb->battleGetMySide();
  933. BNLOG("Player %d: I %s the %s!", playerID % (won ? "won" : "lost") % battlename);
  934. battlename.clear();
  935. CAdventureAI::battleEnd(br);
  936. }
  937. void VCAI::waitTillFree()
  938. {
  939. cb->getGsMutex().unlock_shared();
  940. status.waitTillFree();
  941. cb->getGsMutex().lock_shared();
  942. }
  943. void VCAI::validateVisitableObjs()
  944. {
  945. std::vector<const CGObjectInstance *> hlp;
  946. retreiveVisitableObjs(hlp, true);
  947. start:
  948. BOOST_FOREACH(const CGObjectInstance *obj, visitableObjs)
  949. if(!vstd::contains(hlp, obj))
  950. {
  951. tlog1 << helperObjInfo[obj].name << " at " << helperObjInfo[obj].pos << " shouldn't be on list!\n";
  952. remove_if_present(visitableObjs, obj);
  953. goto start;
  954. }
  955. }
  956. void VCAI::retreiveVisitableObjs(std::vector<const CGObjectInstance *> &out, bool includeOwned /*= false*/) const
  957. {
  958. for(int i = 0; i < cb->getMapSize().x; i++)
  959. for(int j = 0; j < cb->getMapSize().y; j++)
  960. for(int k = 0; k < cb->getMapSize().z; k++)
  961. if(const TerrainTile *t = cb->getTile(int3(i,j,k), false))
  962. BOOST_FOREACH(const CGObjectInstance *obj, t->visitableObjects)
  963. if(includeOwned || obj->tempOwner != playerID)
  964. out.push_back(obj);
  965. }
  966. std::vector<const CGObjectInstance *> VCAI::getFlaggedObjects() const
  967. {
  968. std::vector<const CGObjectInstance *> ret;
  969. retreiveVisitableObjs(ret, true);
  970. erase_if(ret, [](const CGObjectInstance *obj)
  971. {
  972. return obj->tempOwner != ai->playerID;
  973. });
  974. return ret;
  975. }
  976. void VCAI::addVisitableObj(const CGObjectInstance *obj)
  977. {
  978. visitableObjs.push_back(obj);
  979. helperObjInfo[obj] = ObjInfo(obj);
  980. }
  981. const CGObjectInstance * VCAI::lookForArt(int aid) const
  982. {
  983. BOOST_FOREACH(const CGObjectInstance *obj, ai->visitableObjs)
  984. {
  985. if(obj->ID == 5 && obj->subID == aid)
  986. return obj;
  987. }
  988. return NULL;
  989. //TODO what if more than one artifact is available? return them all or some slection criteria
  990. }
  991. bool VCAI::isAccessible(const int3 &pos)
  992. {
  993. //TODO precalculate for speed
  994. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  995. {
  996. if(isAccessibleForHero(pos, h))
  997. return true;
  998. }
  999. return false;
  1000. }
  1001. const CGHeroInstance * VCAI::getHeroWithGrail() const
  1002. {
  1003. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  1004. if(h->hasArt(2)) //grail
  1005. return h;
  1006. return NULL;
  1007. }
  1008. const CGObjectInstance * VCAI::getUnvisitedObj(const boost::function<bool(const CGObjectInstance *)> &predicate)
  1009. {
  1010. //TODO smarter definition of unvisited
  1011. BOOST_FOREACH(const CGObjectInstance *obj, visitableObjs)
  1012. if(predicate(obj) && !vstd::contains(alreadyVisited, obj))
  1013. return obj;
  1014. return NULL;
  1015. }
  1016. bool VCAI::isAccessibleForHero(const int3 & pos, const CGHeroInstance * h) const
  1017. {
  1018. cb->setSelection(h);
  1019. return cb->getPathInfo(pos)->reachable();
  1020. }
  1021. class cannotFulfillGoalException : public std::exception
  1022. {
  1023. std::string msg;
  1024. public:
  1025. explicit cannotFulfillGoalException(crstring _Message) : msg(_Message)
  1026. {
  1027. }
  1028. const char *what() const OVERRIDE
  1029. {
  1030. return msg.c_str();
  1031. }
  1032. };
  1033. bool VCAI::moveHeroToTile(int3 dst, const CGHeroInstance * h)
  1034. {
  1035. int3 startHpos = h->visitablePos();
  1036. bool ret = false;
  1037. if(startHpos == dst)
  1038. {
  1039. assert(cb->getTile(dst)->visitableObjects.size() > 1); //there's no point in revisiting tile where there is no visitable object
  1040. cb->moveHero(h,CGHeroInstance::convertPosition(dst, true));
  1041. waitTillFree(); //movement may cause battle or blocking dialog
  1042. ret = true;
  1043. }
  1044. else
  1045. {
  1046. CGPath path;
  1047. cb->getPath2(dst, path);
  1048. if(path.nodes.empty())
  1049. {
  1050. tlog1 << "Hero " << h->name << " cannot reach " << dst << std::endl;
  1051. throw std::runtime_error("Wrong move order!");
  1052. }
  1053. int i=path.nodes.size()-1;
  1054. for(; i>0; i--)
  1055. {
  1056. //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  1057. if(path.nodes[i-1].turns)
  1058. {
  1059. blockedHeroes.insert(h); //to avoid attempts of moving heroes with very little MPs
  1060. break;
  1061. }
  1062. int3 endpos = path.nodes[i-1].coord;
  1063. if(endpos == h->visitablePos())
  1064. continue;
  1065. // if(i > 1)
  1066. // {
  1067. // int3 afterEndPos = path.nodes[i-2].coord;
  1068. // if(afterEndPos.z != endpos.z)
  1069. //
  1070. // }
  1071. //tlog0 << "Moving " << h->name << " from " << h->getPosition() << " to " << endpos << std::endl;
  1072. cb->moveHero(h,CGHeroInstance::convertPosition(endpos, true));
  1073. waitTillFree(); //movement may cause battle or blocking dialog
  1074. if(h->tempOwner != playerID) //we lost hero
  1075. break;
  1076. boost::this_thread::interruption_point();
  1077. }
  1078. ret = !i;
  1079. }
  1080. if(h->tempOwner == playerID) //lost hero after last move
  1081. cb->recalculatePaths();
  1082. BNLOG("Hero %s moved from %s to %s", h->name % startHpos % h->visitablePos());
  1083. return ret;
  1084. }
  1085. int howManyTilesWillBeDiscovered(const int3 &pos, int radious)
  1086. {
  1087. int ret = 0;
  1088. for(int x = pos.x - radious; x <= pos.x + radious; x++)
  1089. {
  1090. for(int y = pos.y - radious; y <= pos.y + radious; y++)
  1091. {
  1092. int3 npos = int3(x,y,pos.z);
  1093. if(cb->isInTheMap(npos) && pos.dist2d(npos) - 0.5 < radious && !cb->isVisible(npos))
  1094. {
  1095. ret++;
  1096. }
  1097. }
  1098. }
  1099. return ret;
  1100. }
  1101. int howManyTilesWillBeDiscovered(int radious, int3 pos, crint3 dir)
  1102. {
  1103. return howManyTilesWillBeDiscovered(pos + dir, radious);
  1104. }
  1105. void getVisibleNeighbours(const std::vector<int3> &tiles, std::vector<int3> &out)
  1106. {
  1107. BOOST_FOREACH(const int3 &tile, tiles)
  1108. {
  1109. foreach_neighbour(tile, [&](int3 neighbour)
  1110. {
  1111. if(cb->isVisible(neighbour))
  1112. out.push_back(neighbour);
  1113. });
  1114. }
  1115. }
  1116. void VCAI::tryRealize(CGoal g)
  1117. {
  1118. BNLOG("Attempting realizing goal with code %d", g.goalType);
  1119. switch(g.goalType)
  1120. {
  1121. case EXPLORE:
  1122. {
  1123. assert(0); //this goal is not elementar!
  1124. }
  1125. break;
  1126. case RECRUIT_HERO:
  1127. {
  1128. if(const CGTownInstance *t = findTownWithTavern())
  1129. {
  1130. //TODO co jesli nie ma dostepnego bohatera?
  1131. //TODO jezeli miasto jest zablokowane, sprobowac oczyscic wejscie
  1132. cb->recruitHero(t, cb->getAvailableHeroes(t)[0]);
  1133. }
  1134. //TODO karkolomna alternatywa - tawerna na mapie przygod lub wiezienie (nie wiem, czy warto?)
  1135. }
  1136. break;
  1137. case VISIT_TILE:
  1138. {
  1139. if(!g.hero->movement)
  1140. throw cannotFulfillGoalException("Cannot visit tile: hero is out of MPs!");
  1141. if(!g.isBlockedBorderGate(g.tile))
  1142. ai->moveHeroToTile(g.tile, g.hero);
  1143. else
  1144. throw cannotFulfillGoalException("There's a blocked gate!");
  1145. }
  1146. break;
  1147. case BUILD_STRUCTURE:
  1148. {
  1149. const CGTownInstance *t = g.town;
  1150. if(!t && g.hero)
  1151. t = g.hero->visitedTown;
  1152. if(!t)
  1153. {
  1154. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1155. {
  1156. switch(cb->canBuildStructure(t, g.bid))
  1157. {
  1158. case EBuildingState::ALLOWED:
  1159. cb->buildBuilding(t, g.bid);
  1160. return;
  1161. default:
  1162. break;
  1163. }
  1164. }
  1165. }
  1166. else if(cb->canBuildStructure(t, g.bid) == EBuildingState::ALLOWED)
  1167. {
  1168. cb->buildBuilding(t, g.bid);
  1169. return;
  1170. }
  1171. throw cannotFulfillGoalException("Cannot build a given structure!");
  1172. }
  1173. break;
  1174. case DIG_AT_TILE:
  1175. {
  1176. assert(g.hero->visitablePos() == g.tile);
  1177. if(g.hero->diggingStatus() == CGHeroInstance::CAN_DIG)
  1178. cb->dig(g.hero);
  1179. else
  1180. {
  1181. ai->blockedHeroes.insert(g.hero);
  1182. throw cannotFulfillGoalException("A hero can't dig!\n");
  1183. }
  1184. }
  1185. break;
  1186. case COLLECT_RES:
  1187. if(const CGObjectInstance *obj = cb->getObj(g.objid, false))
  1188. {
  1189. if(const IMarket *m = IMarket::castFrom(obj, false))
  1190. {
  1191. for (int i = 0; i < ACTUAL_RESOURCE_COUNT; i++)
  1192. {
  1193. if(i == g.resID) continue;
  1194. int toGive, toGet;
  1195. m->getOffer(i, g.resID, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  1196. toGive = toGive * (cb->getResourceAmount(i) / toGive);
  1197. cb->trade(obj, EMarketMode::RESOURCE_RESOURCE, i, g.resID, toGive);
  1198. if(cb->getResourceAmount(g.resID) >= g.value)
  1199. return;
  1200. }
  1201. }
  1202. else
  1203. {
  1204. throw cannotFulfillGoalException("I don't know how to use this object to raise resources!");
  1205. }
  1206. }
  1207. else
  1208. {
  1209. saving[g.resID] = 1;
  1210. throw cannotFulfillGoalException("No object that could be used to raise resources!");
  1211. }
  1212. case CONQUER:
  1213. // TODO: conquer??
  1214. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1215. case BUILD:
  1216. performTypicalActions();
  1217. throw cannotFulfillGoalException("BUILD has been realized as much as possible.");
  1218. case INVALID:
  1219. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1220. default:
  1221. assert(0);
  1222. }
  1223. }
  1224. const CGTownInstance * VCAI::findTownWithTavern() const
  1225. {
  1226. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1227. if(vstd::contains(t->builtBuildings, EBuilding::TAVERN))
  1228. return t;
  1229. return NULL;
  1230. }
  1231. std::vector<const CGHeroInstance *> VCAI::getUnblockedHeroes() const
  1232. {
  1233. std::vector<const CGHeroInstance *> ret = cb->getHeroesInfo();
  1234. BOOST_FOREACH(const CGHeroInstance *h, blockedHeroes)
  1235. remove_if_present(ret, h);
  1236. return ret;
  1237. }
  1238. const CGHeroInstance * VCAI::primaryHero() const
  1239. {
  1240. auto hs = cb->getHeroesInfo();
  1241. boost::sort(hs, compareHeroStrength);
  1242. if(hs.empty())
  1243. return NULL;
  1244. return hs.back();
  1245. }
  1246. void VCAI::endTurn()
  1247. {
  1248. tlog4 << "Player " << playerID << " ends turn\n";
  1249. if(!status.haveTurn())
  1250. {
  1251. tlog1 << "Not having turn at the end of turn???\n";
  1252. }
  1253. do
  1254. {
  1255. cb->endTurn();
  1256. } 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
  1257. tlog4 << "Player " << playerID << " ended turn\n";
  1258. }
  1259. void VCAI::striveToGoal(const CGoal &ultimateGoal)
  1260. {
  1261. while(1)
  1262. {
  1263. CGoal goal = ultimateGoal;
  1264. BNLOG("Striving to goal of type %d", ultimateGoal.goalType);
  1265. while(!goal.isElementar)
  1266. {
  1267. INDENT;
  1268. BNLOG("Considering goal %d.", goal.goalType);
  1269. try
  1270. {
  1271. boost::this_thread::interruption_point();
  1272. goal = goal.whatToDoToAchieve();
  1273. }
  1274. catch(std::exception &e)
  1275. {
  1276. BNLOG("Goal %d decomposition failed: %s", goal.goalType % e.what());
  1277. return;
  1278. }
  1279. }
  1280. try
  1281. {
  1282. boost::this_thread::interruption_point();
  1283. tryRealize(goal);
  1284. boost::this_thread::interruption_point();
  1285. }
  1286. catch(boost::thread_interrupted &e)
  1287. {
  1288. BNLOG("Player %d: Making turn thread received an interruption!", playerID);
  1289. throw; //rethrow, we want to truly end this thread
  1290. }
  1291. catch(std::exception &e)
  1292. {
  1293. BNLOG("Failed to realize subgoal of type %d (greater goal type was %d), I will stop.", goal.goalType % ultimateGoal.goalType);
  1294. BNLOG("The error message was: %s", e.what());
  1295. break;
  1296. }
  1297. }
  1298. }
  1299. void VCAI::performTypicalActions()
  1300. {
  1301. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1302. {
  1303. BNLOG("Looking into %s", t->name);
  1304. buildStructure(t);
  1305. buildArmyIn(t);
  1306. if(!ai->primaryHero() ||
  1307. t->getArmyStrength() > ai->primaryHero()->getArmyStrength() * 2 && !isAccessibleForHero(t->visitablePos(), ai->primaryHero()))
  1308. {
  1309. recruitHero(t);
  1310. buildArmyIn(t);
  1311. }
  1312. }
  1313. BOOST_FOREACH(const CGHeroInstance *h, getUnblockedHeroes())
  1314. {
  1315. BNLOG("Looking into %s, MP=%d", h->name.c_str() % h->movement);
  1316. INDENT;
  1317. makePossibleUpgrades(h);
  1318. cb->setSelection(h);
  1319. wander(h);
  1320. }
  1321. }
  1322. void VCAI::buildArmyIn(const CGTownInstance * t)
  1323. {
  1324. makePossibleUpgrades(t->visitingHero);
  1325. makePossibleUpgrades(t);
  1326. recruitCreatures(t);
  1327. moveCreaturesToHero(t);
  1328. }
  1329. int3 VCAI::explorationBestNeighbour(int3 hpos, int radius, const CGHeroInstance * h)
  1330. {
  1331. TimeCheck tc("looking for best exploration neighbour");
  1332. std::map<int3, int> dstToRevealedTiles;
  1333. BOOST_FOREACH(crint3 dir, dirs)
  1334. if(cb->isInTheMap(hpos+dir))
  1335. dstToRevealedTiles[hpos + dir] = howManyTilesWillBeDiscovered(radius, hpos, dir) * isSafeToVisit(h, hpos + dir);
  1336. auto best = dstToRevealedTiles.begin();
  1337. best->second *= cb->getPathInfo(best->first)->reachable();
  1338. best->second *= cb->getPathInfo(best->first)->accessible == CGPathNode::ACCESSIBLE;
  1339. for(auto i = dstToRevealedTiles.begin(); i != dstToRevealedTiles.end(); i++)
  1340. {
  1341. const CGPathNode *pn = cb->getPathInfo(i->first);
  1342. const TerrainTile *t = cb->getTile(i->first);
  1343. if(best->second < i->second && i->second && pn->reachable() && pn->accessible == CGPathNode::ACCESSIBLE)
  1344. best = i;
  1345. }
  1346. if(best->second)
  1347. return best->first;
  1348. throw cannotFulfillGoalException("No neighbour will bring new discoveries!");
  1349. }
  1350. int3 VCAI::explorationNewPoint(int radius, const CGHeroInstance * h, std::vector<std::vector<int3> > &tiles)
  1351. {
  1352. TimeCheck tc("looking for new exploration point");
  1353. tlog0 << "Looking for an another place for exploration...\n";
  1354. tiles.resize(radius);
  1355. foreach_tile_pos([&](const int3 &pos)
  1356. {
  1357. if(!cb->isVisible(pos))
  1358. tiles[0].push_back(pos);
  1359. });
  1360. for (int i = 1; i < radius; i++)
  1361. {
  1362. getVisibleNeighbours(tiles[i-1], tiles[i]);
  1363. removeDuplicates(tiles[i]);
  1364. BOOST_FOREACH(const int3 &tile, tiles[i])
  1365. {
  1366. if(cb->getPathInfo(tile)->reachable() && isSafeToVisit(h, tile) && howManyTilesWillBeDiscovered(tile, radius))
  1367. {
  1368. return tile;
  1369. }
  1370. }
  1371. }
  1372. throw cannotFulfillGoalException("No accessible tile will bring discoveries!");
  1373. }
  1374. TResources VCAI::estimateIncome() const
  1375. {
  1376. TResources ret;
  1377. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1378. {
  1379. ret[Res::GOLD] += t->dailyIncome();
  1380. //TODO duplikuje newturn
  1381. if(t->hasBuilt(EBuilding::RESOURCE_SILO)) //there is resource silo
  1382. {
  1383. if(t->town->primaryRes == 127) //we'll give wood and ore
  1384. {
  1385. ret[Res::WOOD] ++;
  1386. ret[Res::ORE] ++;
  1387. }
  1388. else
  1389. {
  1390. ret[t->town->primaryRes] ++;
  1391. }
  1392. }
  1393. }
  1394. BOOST_FOREACH(const CGObjectInstance *obj, getFlaggedObjects())
  1395. {
  1396. if(obj->ID == Obj::MINE)
  1397. {
  1398. switch(obj->subID)
  1399. {
  1400. case Res::WOOD:
  1401. case Res::ORE:
  1402. ret[obj->subID] += WOOD_ORE_MINE_PRODUCTION;
  1403. break;
  1404. case Res::GOLD:
  1405. case 7: //abandoned mine -> also gold
  1406. ret[Res::GOLD] += GOLD_MINE_PRODUCTION;
  1407. break;
  1408. default:
  1409. ret[obj->subID] += RESOURCE_MINE_PRODUCTION;
  1410. break;
  1411. }
  1412. }
  1413. }
  1414. return ret;
  1415. }
  1416. bool VCAI::containsSavedRes(const TResources &cost) const
  1417. {
  1418. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  1419. {
  1420. if(saving[i] && cost[i])
  1421. return true;
  1422. }
  1423. return false;
  1424. }
  1425. void VCAI::recruitHero(const CGTownInstance * t)
  1426. {
  1427. BNLOG("Trying to recruit a hero in %s at %s", t->name % t->visitablePos())
  1428. cb->recruitHero(t, cb->getAvailableHeroes(t).front());
  1429. }
  1430. AIStatus::AIStatus()
  1431. {
  1432. battle = NO_BATTLE;
  1433. remainingQueries = 0;
  1434. havingTurn = false;
  1435. }
  1436. AIStatus::~AIStatus()
  1437. {
  1438. }
  1439. void AIStatus::setBattle(BattleState BS)
  1440. {
  1441. boost::unique_lock<boost::mutex> lock(mx);
  1442. battle = BS;
  1443. cv.notify_all();
  1444. }
  1445. BattleState AIStatus::getBattle()
  1446. {
  1447. boost::unique_lock<boost::mutex> lock(mx);
  1448. return battle;
  1449. }
  1450. void AIStatus::addQueries(int val)
  1451. {
  1452. boost::unique_lock<boost::mutex> lock(mx);
  1453. remainingQueries += val;
  1454. BNLOG("Changing count of queries by %d, to a total of %d", val % remainingQueries);
  1455. assert(remainingQueries >= 0);
  1456. cv.notify_all();
  1457. }
  1458. void AIStatus::addQuery()
  1459. {
  1460. addQueries(1);
  1461. }
  1462. void AIStatus::removeQuery()
  1463. {
  1464. addQueries(-1);
  1465. }
  1466. int AIStatus::getQueriesCount()
  1467. {
  1468. boost::unique_lock<boost::mutex> lock(mx);
  1469. return remainingQueries;
  1470. }
  1471. void AIStatus::startedTurn()
  1472. {
  1473. boost::unique_lock<boost::mutex> lock(mx);
  1474. havingTurn = true;
  1475. cv.notify_all();
  1476. }
  1477. void AIStatus::madeTurn()
  1478. {
  1479. boost::unique_lock<boost::mutex> lock(mx);
  1480. havingTurn = false;
  1481. cv.notify_all();
  1482. }
  1483. void AIStatus::waitTillFree()
  1484. {
  1485. boost::unique_lock<boost::mutex> lock(mx);
  1486. while(battle != NO_BATTLE || remainingQueries)
  1487. cv.wait(lock);
  1488. }
  1489. bool AIStatus::haveTurn()
  1490. {
  1491. boost::unique_lock<boost::mutex> lock(mx);
  1492. return havingTurn;
  1493. }
  1494. int3 whereToExplore(const CGHeroInstance *h)
  1495. {
  1496. //TODO it's stupid and ineffective, write sth better
  1497. cb->setSelection(h);
  1498. int radius = h->getSightRadious();
  1499. int3 hpos = h->visitablePos();
  1500. //look for nearby objs -> visit them if they're close enouh
  1501. const int DIST_LIMIT = 3;
  1502. std::vector<const CGObjectInstance *> nearbyVisitableObjs;
  1503. BOOST_FOREACH(const CGObjectInstance *obj, ai->getPossibleDestinations(h))
  1504. {
  1505. int3 op = obj->visitablePos();
  1506. CGPath p;
  1507. cb->getPath2(op, p);
  1508. if(p.nodes.size() && p.endPos() == op && p.nodes.size() <= DIST_LIMIT)
  1509. nearbyVisitableObjs.push_back(obj);
  1510. }
  1511. boost::sort(nearbyVisitableObjs, isCloser);
  1512. if(nearbyVisitableObjs.size())
  1513. return nearbyVisitableObjs.back()->visitablePos();
  1514. try
  1515. {
  1516. return ai->explorationBestNeighbour(hpos, radius, h);
  1517. }
  1518. catch(cannotFulfillGoalException &e)
  1519. {
  1520. std::vector<std::vector<int3> > tiles; //tiles[distance_to_fow], metryka taksówkowa
  1521. try
  1522. {
  1523. return ai->explorationNewPoint(radius, h, tiles);
  1524. }
  1525. catch(cannotFulfillGoalException &e)
  1526. {
  1527. std::map<int, std::vector<int3> > profits;
  1528. {
  1529. TimeCheck tc("Evaluating exploration possibilities");
  1530. tiles[0].clear(); //we can't reach FoW anyway
  1531. BOOST_FOREACH(auto &vt, tiles)
  1532. BOOST_FOREACH(auto &tile, vt)
  1533. profits[howManyTilesWillBeDiscovered(tile, radius)].push_back(tile);
  1534. }
  1535. if(profits.empty())
  1536. throw cannotFulfillGoalException("Cannot explore - no possible ways found!");
  1537. auto bestDest = profits.end();
  1538. bestDest--;
  1539. return bestDest->second.front(); //TODO which is the real best tile?
  1540. }
  1541. }
  1542. }
  1543. TSubgoal CGoal::whatToDoToAchieve()
  1544. {
  1545. switch(goalType)
  1546. {
  1547. case WIN:
  1548. {
  1549. const CVictoryCondition &vc = cb->getMapHeader()->victoryCondition;
  1550. EVictoryConditionType::EVictoryConditionType cond = vc.condition;
  1551. if(!vc.appliesToAI)
  1552. {
  1553. //TODO deduce victory from human loss condition
  1554. cond = EVictoryConditionType::WINSTANDARD;
  1555. }
  1556. switch(cond)
  1557. {
  1558. case EVictoryConditionType::ARTIFACT:
  1559. return CGoal(GET_ART_TYPE).setaid(vc.ID);
  1560. case EVictoryConditionType::BEATHERO:
  1561. return CGoal(GET_OBJ).setobjid(vc.ID);
  1562. case EVictoryConditionType::BEATMONSTER:
  1563. return CGoal(GET_OBJ).setobjid(vc.ID);
  1564. case EVictoryConditionType::BUILDCITY:
  1565. //TODO build castle/capitol
  1566. break;
  1567. case EVictoryConditionType::BUILDGRAIL:
  1568. {
  1569. if(const CGHeroInstance *h = ai->getHeroWithGrail())
  1570. {
  1571. //hero is in a town that can host Grail
  1572. if(h->visitedTown && !vstd::contains(h->visitedTown->forbiddenBuildings, EBuilding::GRAIL))
  1573. {
  1574. const CGTownInstance *t = h->visitedTown;
  1575. return CGoal(BUILD_STRUCTURE).setbid(EBuilding::GRAIL).settown(t);
  1576. }
  1577. else
  1578. {
  1579. auto towns = cb->getTownsInfo();
  1580. towns.erase(boost::remove_if(towns,
  1581. [](const CGTownInstance *t) -> bool
  1582. {
  1583. return vstd::contains(t->forbiddenBuildings, EBuilding::GRAIL);
  1584. }),
  1585. towns.end());
  1586. boost::sort(towns, isCloser);
  1587. if(towns.size())
  1588. {
  1589. return CGoal(VISIT_TILE).sethero(h).settile(towns.front()->visitablePos());
  1590. }
  1591. }
  1592. }
  1593. double ratio = 0;
  1594. int3 grailPos = cb->getGrailPos(ratio);
  1595. if(ratio > 0.99)
  1596. {
  1597. return CGoal(DIG_AT_TILE).settile(grailPos);
  1598. }
  1599. else if(const CGObjectInstance * obj = ai->getUnvisitedObj(objWithID<Obj::OBELISK>)) //there are unvisited Obelisks
  1600. {
  1601. return CGoal(GET_OBJ).setobjid(obj->id);
  1602. }
  1603. else
  1604. return CGoal(EXPLORE);
  1605. }
  1606. break;
  1607. case EVictoryConditionType::CAPTURECITY:
  1608. return CGoal(GET_OBJ).setobjid(vc.ID);
  1609. case EVictoryConditionType::GATHERRESOURCE:
  1610. return CGoal(COLLECT_RES).setresID(vc.ID).setvalue(vc.count);
  1611. //TODO mines? piles? marketplace?
  1612. //save?
  1613. break;
  1614. case EVictoryConditionType::GATHERTROOP:
  1615. break;
  1616. case EVictoryConditionType::TAKEDWELLINGS:
  1617. break;
  1618. case EVictoryConditionType::TAKEMINES:
  1619. break;
  1620. case EVictoryConditionType::TRANSPORTITEM:
  1621. break;
  1622. case EVictoryConditionType::WINSTANDARD:
  1623. return CGoal(CONQUER);
  1624. default:
  1625. assert(0);
  1626. }
  1627. }
  1628. break;
  1629. case GET_OBJ:
  1630. {
  1631. const CGObjectInstance * obj = cb->getObj(objid);
  1632. if(!obj)
  1633. return CGoal(EXPLORE);
  1634. int3 pos = cb->getObj(objid)->visitablePos();
  1635. return CGoal(VISIT_TILE).settile(pos);
  1636. }
  1637. break;
  1638. case GET_ART_TYPE:
  1639. {
  1640. const CGObjectInstance *artInst = ai->lookForArt(aid);
  1641. if(!artInst)
  1642. {
  1643. TSubgoal alternativeWay = CGoal::lookForArtSmart(aid);
  1644. if(alternativeWay.invalid())
  1645. return CGoal(EXPLORE);
  1646. else
  1647. return alternativeWay;
  1648. }
  1649. else
  1650. return CGoal(GET_OBJ).setobjid(artInst->id);
  1651. }
  1652. break;
  1653. case CLEAR_WAY_TO:
  1654. {
  1655. assert(tile.x >= 0); //set tile
  1656. if(!cb->isVisible(tile))
  1657. {
  1658. tlog1 << "Clear way should be used with visible tiles!\n";
  1659. return CGoal(EXPLORE);
  1660. }
  1661. const CGHeroInstance *h = hero ? hero : ai->primaryHero();
  1662. if(!h)
  1663. return CGoal(RECRUIT_HERO);
  1664. cb->setSelection(h);
  1665. SectorMap sm;
  1666. bool dropToFile = false;
  1667. if(dropToFile) //for debug purposes
  1668. sm.write("test.txt");
  1669. int3 tileToHit = sm.firstTileToGet(h, tile);
  1670. //if(isSafeToVisit(h, tileToHit))
  1671. if(isBlockedBorderGate(tileToHit))
  1672. throw cannotFulfillGoalException("There's blocked border gate!");
  1673. if(tileToHit == tile)
  1674. {
  1675. tlog1 << boost::format("Very strange, tile to hit is %s and tile is also %s, while hero %s is at %s\n")
  1676. % tileToHit % tile % h->name % h->visitablePos();
  1677. throw cannotFulfillGoalException("Retreiving first tile to hit failed (probably)!");
  1678. }
  1679. return CGoal(VISIT_TILE).settile(tileToHit).sethero(h);
  1680. //TODO czy istnieje lepsza droga?
  1681. }
  1682. throw cannotFulfillGoalException("Cannot reach given tile!");
  1683. //return CGoal(EXPLORE); // TODO improve
  1684. case EXPLORE:
  1685. {
  1686. if(cb->getHeroesInfo().empty())
  1687. return CGoal(RECRUIT_HERO);
  1688. auto hs = cb->getHeroesInfo();
  1689. assert(hs.size());
  1690. erase(hs, [](const CGHeroInstance *h)
  1691. {
  1692. return !h->movement || contains(ai->blockedHeroes, h); //only hero with movement are of interest for us
  1693. });
  1694. if(hs.empty())
  1695. {
  1696. throw cannotFulfillGoalException("No heroes with remaining MPs for exploring!\n");
  1697. }
  1698. const CGHeroInstance *h = hs.front();
  1699. CGoal ret(VISIT_TILE);
  1700. ret.sethero(h);
  1701. return ret.settile(whereToExplore(h));
  1702. }
  1703. I_AM_ELEMENTAR;
  1704. case RECRUIT_HERO:
  1705. {
  1706. const CGTownInstance *t = ai->findTownWithTavern();
  1707. if(!t)
  1708. return CGoal(BUILD_STRUCTURE).setbid(EBuilding::TAVERN);
  1709. if(cb->getResourceAmount(Res::GOLD) < HERO_GOLD_COST)
  1710. return CGoal(COLLECT_RES).setresID(Res::GOLD).setvalue(HERO_GOLD_COST);
  1711. I_AM_ELEMENTAR;
  1712. }
  1713. break;
  1714. case VISIT_TILE:
  1715. {
  1716. if(!cb->isVisible(tile))
  1717. return CGoal(EXPLORE);
  1718. if(hero && !ai->isAccessibleForHero(tile, hero))
  1719. hero = NULL;
  1720. if(!hero)
  1721. {
  1722. if(cb->getHeroesInfo().empty())
  1723. return CGoal(RECRUIT_HERO);
  1724. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  1725. {
  1726. if(ai->isAccessibleForHero(tile, h))
  1727. {
  1728. hero = h;
  1729. break;
  1730. }
  1731. }
  1732. }
  1733. if(hero)
  1734. {
  1735. if(isSafeToVisit(hero, tile))
  1736. return CGoal(*this).setisElementar(true);
  1737. else
  1738. return CGoal(INVALID); //todo can gather army?
  1739. }
  1740. else //inaccessible for all heroes
  1741. return CGoal(CLEAR_WAY_TO).settile(tile);
  1742. }
  1743. break;
  1744. case DIG_AT_TILE:
  1745. {
  1746. auto objs = cb->getTile(tile)->visitableObjects;
  1747. if(objs.size() && objs.front()->ID == GameConstants::HEROI_TYPE && objs.front()->tempOwner == ai->playerID) //we have hero at dest
  1748. {
  1749. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(objs.front());
  1750. return CGoal(*this).sethero(h).setisElementar(true);
  1751. }
  1752. return CGoal(VISIT_TILE).settile(tile);
  1753. }
  1754. break;
  1755. case BUILD_STRUCTURE:
  1756. //TODO check res
  1757. //look for town
  1758. //prerequisites?
  1759. I_AM_ELEMENTAR;
  1760. case COLLECT_RES:
  1761. {
  1762. std::vector<const IMarket*> markets;
  1763. std::vector<const CGObjectInstance*> visObjs;
  1764. ai->retreiveVisitableObjs(visObjs, true);
  1765. BOOST_FOREACH(const CGObjectInstance *obj, visObjs)
  1766. {
  1767. if(const IMarket *m = IMarket::castFrom(obj, false))
  1768. {
  1769. if(obj->ID == GameConstants::TOWNI_TYPE && obj->tempOwner == ai->playerID && m->allowsTrade(EMarketMode::RESOURCE_RESOURCE))
  1770. markets.push_back(m);
  1771. else if(obj->ID == Obj::TRADING_POST) //TODO a moze po prostu test na pozwalanie handlu?
  1772. markets.push_back(m);
  1773. }
  1774. }
  1775. boost::sort(markets, [](const IMarket *m1, const IMarket *m2) -> bool
  1776. {
  1777. return m1->getMarketEfficiency() < m2->getMarketEfficiency();
  1778. });
  1779. markets.erase(boost::remove_if(markets, [](const IMarket *market) -> bool
  1780. {
  1781. return !(market->o->ID == GameConstants::TOWNI_TYPE && market->o->tempOwner == ai->playerID)
  1782. && !ai->isAccessible(market->o->visitablePos());
  1783. }),markets.end());
  1784. if(!markets.size())
  1785. {
  1786. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1787. {
  1788. if(cb->canBuildStructure(t, EBuilding::MARKETPLACE) == EBuildingState::ALLOWED)
  1789. return CGoal(BUILD_STRUCTURE).settown(t).setbid(EBuilding::MARKETPLACE);
  1790. }
  1791. }
  1792. else
  1793. {
  1794. const IMarket *m = markets.back();
  1795. //attempt trade at back (best prices)
  1796. int howManyCanWeBuy = 0;
  1797. for(int i = 0; i < ACTUAL_RESOURCE_COUNT; i++)
  1798. {
  1799. if(i == resID) continue;
  1800. int toGive = -1, toReceive = -1;
  1801. m->getOffer(i, resID, toGive, toReceive, EMarketMode::RESOURCE_RESOURCE);
  1802. assert(toGive > 0 && toReceive > 0);
  1803. howManyCanWeBuy += toReceive * (cb->getResourceAmount(i) / toGive);
  1804. }
  1805. if(howManyCanWeBuy + cb->getResourceAmount(resID) >= value)
  1806. {
  1807. if(cb->getTile(m->o->visitablePos())->visitableObjects.back()->tempOwner != ai->playerID)
  1808. return CGoal(GET_OBJ).setobjid(m->o->id);
  1809. return setobjid(m->o->id).setisElementar(true);
  1810. }
  1811. }
  1812. }
  1813. return CGoal(INVALID);
  1814. case CONQUER:
  1815. {
  1816. //TODO make use from many heroes
  1817. std::vector<const CGHeroInstance *> heroes = cb->getHeroesInfo();
  1818. erase_if(heroes, [](const CGHeroInstance *h)
  1819. {
  1820. return vstd::contains(ai->blockedHeroes, h) || !h->movement;
  1821. });
  1822. boost::sort(heroes, compareHeroStrength);
  1823. if(heroes.empty())
  1824. I_AM_ELEMENTAR;
  1825. const CGHeroInstance *h = heroes.back();
  1826. cb->setSelection(h);
  1827. std::vector<const CGObjectInstance *> objs; //here we'll gather enemy towns and heroes
  1828. ai->retreiveVisitableObjs(objs);
  1829. erase_if(objs, [&](const CGObjectInstance *obj)
  1830. {
  1831. return obj->ID != GameConstants::TOWNI_TYPE && obj->ID != GameConstants::HEROI_TYPE //not town/hero
  1832. || cb->getPlayerRelations(ai->playerID, obj->tempOwner) != 0; //not enemy
  1833. });
  1834. if(objs.empty())
  1835. return CGoal(EXPLORE); //we need to find an enemy
  1836. erase_if(objs, [&](const CGObjectInstance *obj)
  1837. {
  1838. return !isSafeToVisit(h, obj->visitablePos());
  1839. });
  1840. if(objs.empty())
  1841. I_AM_ELEMENTAR;
  1842. boost::sort(objs, isCloser);
  1843. BOOST_FOREACH(const CGObjectInstance *obj, objs)
  1844. {
  1845. if(ai->isAccessibleForHero(obj->visitablePos(), h))
  1846. return CGoal(VISIT_TILE).sethero(h).settile(obj->visitablePos());
  1847. }
  1848. return CGoal(EXPLORE); //enemy is inaccessible
  1849. ;
  1850. }
  1851. break;
  1852. case BUILD:
  1853. I_AM_ELEMENTAR;
  1854. case INVALID:
  1855. I_AM_ELEMENTAR;
  1856. default:
  1857. assert(0);
  1858. }
  1859. return CGoal(EXPLORE);
  1860. }
  1861. TSubgoal CGoal::goVisitOrLookFor(const CGObjectInstance *obj)
  1862. {
  1863. if(obj)
  1864. return CGoal(GET_OBJ).setobjid(obj->id);
  1865. else
  1866. return CGoal(EXPLORE);
  1867. }
  1868. TSubgoal CGoal::lookForArtSmart(int aid)
  1869. {
  1870. return CGoal(INVALID);
  1871. }
  1872. bool CGoal::invalid() const
  1873. {
  1874. return goalType == INVALID;
  1875. }
  1876. bool CGoal::isBlockedBorderGate(int3 tileToHit)
  1877. {
  1878. return cb->getTile(tileToHit)->topVisitableID() == Obj::BORDER_GATE
  1879. && cb->getPathInfo(tileToHit)->accessible != CGPathNode::ACCESSIBLE;
  1880. }
  1881. SectorMap::SectorMap()
  1882. {
  1883. // int3 sizes = cb->getMapSize();
  1884. // sector.resize(sizes.x);
  1885. // BOOST_FOREACH(auto &i, sector)
  1886. // i.resize(sizes.y);
  1887. //
  1888. // BOOST_FOREACH(auto &i, sector)
  1889. // BOOST_FOREACH(auto &j, i)
  1890. // j.resize(sizes.z, 0);
  1891. update();
  1892. }
  1893. bool markIfBlocked(ui8 &sec, crint3 pos, const TerrainTile *t)
  1894. {
  1895. if(t->blocked && !t->visitable)
  1896. {
  1897. sec = NOT_AVAILABLE;
  1898. return true;
  1899. }
  1900. return false;
  1901. }
  1902. bool markIfBlocked(ui8 &sec, crint3 pos)
  1903. {
  1904. return markIfBlocked(sec, pos, cb->getTile(pos));
  1905. }
  1906. void SectorMap::update()
  1907. {
  1908. clear();
  1909. int curSector = 3; //0 is invisible, 1 is not explored
  1910. foreach_tile_pos([&](crint3 pos)
  1911. {
  1912. if(retreiveTile(pos) == NOT_CHECKED)
  1913. {
  1914. if(!markIfBlocked(retreiveTile(pos), pos))
  1915. exploreNewSector(pos, curSector++);
  1916. }
  1917. });
  1918. valid = true;
  1919. }
  1920. void SectorMap::clear()
  1921. {
  1922. sector = cb->getVisibilityMap();
  1923. valid = false;
  1924. }
  1925. bool canBeEmbarkmentPoint(const TerrainTile *t)
  1926. {
  1927. //tile must be free of with unoccupied boat
  1928. return !t->blocked
  1929. || t->visitableObjects.size() == 1 && t->topVisitableID() == Obj::BOAT;
  1930. }
  1931. void SectorMap::exploreNewSector(crint3 pos, int num)
  1932. {
  1933. Sector &s = infoOnSectors[num];
  1934. s.id = num;
  1935. s.water = cb->getTile(pos)->isWater();
  1936. std::queue<int3> toVisit;
  1937. toVisit.push(pos);
  1938. while(toVisit.size())
  1939. {
  1940. int3 curPos = toVisit.front();
  1941. toVisit.pop();
  1942. ui8 &sec = retreiveTile(curPos);
  1943. if(sec == NOT_CHECKED)
  1944. {
  1945. const TerrainTile *t = cb->getTile(curPos);
  1946. if(!markIfBlocked(sec, curPos, t))
  1947. {
  1948. if(t->isWater() == s.water) //sector is only-water or only-land
  1949. {
  1950. sec = num;
  1951. s.tiles.push_back(curPos);
  1952. foreach_neighbour(curPos, [&](crint3 neighPos)
  1953. {
  1954. if(retreiveTile(neighPos) == NOT_CHECKED)
  1955. {
  1956. toVisit.push(neighPos);
  1957. //parent[neighPos] = curPos;
  1958. }
  1959. const TerrainTile *nt = cb->getTile(neighPos, false);
  1960. if(nt && nt->isWater() != s.water && canBeEmbarkmentPoint(nt))
  1961. {
  1962. s.embarkmentPoints.push_back(neighPos);
  1963. }
  1964. });
  1965. if(t->visitable && vstd::contains(ai->knownSubterraneanGates, t->visitableObjects.front()))
  1966. toVisit.push(ai->knownSubterraneanGates[t->visitableObjects.front()]->pos);
  1967. }
  1968. }
  1969. }
  1970. }
  1971. removeDuplicates(s.embarkmentPoints);
  1972. }
  1973. void SectorMap::write(crstring fname)
  1974. {
  1975. std::ofstream out(fname);
  1976. for(int k = 0; k < cb->getMapSize().z; k++)
  1977. {
  1978. for(int j = 0; j < cb->getMapSize().y; j++)
  1979. {
  1980. for(int i = 0; i < cb->getMapSize().x; i++)
  1981. {
  1982. out << (int)sector[i][j][k] << '\t';
  1983. }
  1984. out << std::endl;
  1985. }
  1986. out << std::endl;
  1987. }
  1988. }
  1989. int3 SectorMap::firstTileToGet(const CGHeroInstance *h, crint3 dst)
  1990. {
  1991. int sourceSector = retreiveTile(h->visitablePos()),
  1992. destinationSector = retreiveTile(dst);
  1993. if(sourceSector != destinationSector)
  1994. {
  1995. const Sector *src = &infoOnSectors[sourceSector],
  1996. *dst = &infoOnSectors[destinationSector];
  1997. std::map<const Sector*, const Sector*> preds;
  1998. std::queue<const Sector *> sq;
  1999. sq.push(src);
  2000. while(!sq.empty())
  2001. {
  2002. const Sector *s = sq.front();
  2003. sq.pop();
  2004. BOOST_FOREACH(int3 ep, s->embarkmentPoints)
  2005. {
  2006. Sector *neigh = &infoOnSectors[retreiveTile(ep)];
  2007. //preds[s].push_back(neigh);
  2008. if(!preds[neigh])
  2009. {
  2010. preds[neigh] = s;
  2011. sq.push(neigh);
  2012. }
  2013. }
  2014. //TODO consider other types of connections between sectors?
  2015. }
  2016. if(!preds[dst])
  2017. {
  2018. write("test.txt");
  2019. throw cannotFulfillGoalException(str(format("Cannot found connection between sectors %d and %d") % src->id % dst->id));
  2020. }
  2021. std::vector<const Sector*> toTraverse;
  2022. toTraverse.push_back(dst);
  2023. while(toTraverse.back() != src)
  2024. {
  2025. toTraverse.push_back(preds[toTraverse.back()]);
  2026. }
  2027. if(preds[dst])
  2028. {
  2029. const Sector *sectorToReach = toTraverse.at(toTraverse.size() - 2);
  2030. if(!src->water && sectorToReach->water) //embark
  2031. {
  2032. //embark on ship -> look for an EP with a boat
  2033. auto firstEP = boost::find_if(src->embarkmentPoints, [=](crint3 pos) -> bool
  2034. {
  2035. const TerrainTile *t = cb->getTile(pos);
  2036. return t && t->visitableObjects.size() == 1 && t->topVisitableID() == Obj::BOAT
  2037. && retreiveTile(pos) == sectorToReach->id;
  2038. });
  2039. if(firstEP != src->embarkmentPoints.end())
  2040. {
  2041. return *firstEP;
  2042. }
  2043. else
  2044. {
  2045. //we need to find a shipyard with an access to the desired sector's EP
  2046. //TODO what about Summon Boat spell?
  2047. std::vector<const IShipyard *> shipyards;
  2048. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  2049. {
  2050. if(t->hasBuilt(EBuilding::SHIPYARD))
  2051. shipyards.push_back(t);
  2052. }
  2053. std::vector<const CGObjectInstance*> visObjs;
  2054. ai->retreiveVisitableObjs(visObjs, true);
  2055. BOOST_FOREACH(const CGObjectInstance *obj, visObjs)
  2056. {
  2057. if(obj->ID != GameConstants::TOWNI_TYPE) //towns were handled in the previous loop
  2058. if(const IShipyard *shipyard = IShipyard::castFrom(obj))
  2059. shipyards.push_back(shipyard);
  2060. }
  2061. shipyards.erase(boost::remove_if(shipyards, [=](const IShipyard *shipyard) -> bool
  2062. {
  2063. return shipyard->state() != 0 || retreiveTile(shipyard->bestLocation()) != sectorToReach->id;
  2064. }),shipyards.end());
  2065. if(!shipyards.size())
  2066. {
  2067. //TODO consider possibility of building shipyard in a town
  2068. throw cannotFulfillGoalException("There is no known shipyard!");
  2069. }
  2070. //we have only shipyards that possibly can build ships onto the appropriate EP
  2071. auto ownedGoodShipyard = boost::find_if(shipyards, [](const IShipyard *s) -> bool
  2072. {
  2073. return s->o->tempOwner == ai->playerID;
  2074. });
  2075. if(ownedGoodShipyard != shipyards.end())
  2076. {
  2077. const IShipyard *s = *ownedGoodShipyard;
  2078. TResources shipCost;
  2079. s->getBoatCost(shipCost);
  2080. if(cb->getResourceAmount().canAfford(shipCost))
  2081. {
  2082. int3 ret = s->bestLocation();
  2083. cb->buildBoat(s);
  2084. return ret;
  2085. }
  2086. else
  2087. {
  2088. //TODO gather res
  2089. throw cannotFulfillGoalException("Not enough resources to build a boat");
  2090. }
  2091. }
  2092. else
  2093. {
  2094. //TODO pick best shipyard to take over
  2095. return shipyards.front()->o->pos;
  2096. }
  2097. }
  2098. }
  2099. else if(src->water && !sectorToReach->water)
  2100. {
  2101. //TODO
  2102. //disembark
  2103. }
  2104. else
  2105. {
  2106. //TODO
  2107. //transition between two land/water sectors. Monolith? Whirlpool? ...
  2108. throw cannotFulfillGoalException("Land-land and water-water inter-sector transitions are not implemented!");
  2109. }
  2110. }
  2111. else
  2112. {
  2113. throw cannotFulfillGoalException("Inter-sector route detection failed: not connected sectors?");
  2114. }
  2115. }
  2116. else
  2117. {
  2118. makeParentBFS(h->visitablePos());
  2119. int3 curtile = dst;
  2120. while(curtile != h->visitablePos())
  2121. {
  2122. if(cb->getPathInfo(curtile)->reachable())
  2123. {
  2124. return curtile;
  2125. }
  2126. else
  2127. {
  2128. auto i = parent.find(curtile);
  2129. if(i != parent.end())
  2130. {
  2131. assert(curtile != i->second);
  2132. curtile = i->second;
  2133. }
  2134. else
  2135. throw cannotFulfillGoalException("Unreachable tile in sector? Should not happen!");
  2136. }
  2137. }
  2138. }
  2139. throw cannotFulfillGoalException("Impossible happened.");
  2140. }
  2141. void SectorMap::makeParentBFS(crint3 source)
  2142. {
  2143. parent.clear();
  2144. int mySector = retreiveTile(source);
  2145. std::queue<int3> toVisit;
  2146. toVisit.push(source);
  2147. while(toVisit.size())
  2148. {
  2149. int3 curPos = toVisit.front();
  2150. toVisit.pop();
  2151. ui8 &sec = retreiveTile(curPos);
  2152. assert(sec == mySector); //consider only tiles from the same sector
  2153. const TerrainTile *t = cb->getTile(curPos);
  2154. foreach_neighbour(curPos, [&](crint3 neighPos)
  2155. {
  2156. if(retreiveTile(neighPos) == mySector && !vstd::contains(parent, neighPos))
  2157. {
  2158. toVisit.push(neighPos);
  2159. parent[neighPos] = curPos;
  2160. }
  2161. });
  2162. }
  2163. }
  2164. unsigned char & SectorMap::retreiveTile(crint3 pos)
  2165. {
  2166. return retreiveTileN(sector, pos);
  2167. }