Goals.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483
  1. /*
  2. * Goals.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "Goals.h"
  12. #include "VCAI.h"
  13. #include "Fuzzy.h"
  14. #include "ResourceManager.h"
  15. #include "../../lib/mapping/CMap.h" //for victory conditions
  16. #include "../../lib/CPathfinder.h"
  17. #include "../../lib/StringConstants.h"
  18. #include "AIhelper.h"
  19. extern boost::thread_specific_ptr<CCallback> cb;
  20. extern boost::thread_specific_ptr<VCAI> ai;
  21. extern boost::thread_specific_ptr<AIhelper> ah;
  22. extern FuzzyHelper * fh;
  23. using namespace Goals;
  24. TSubgoal Goals::sptr(const AbstractGoal & tmp)
  25. {
  26. TSubgoal ptr;
  27. ptr.reset(tmp.clone());
  28. return ptr;
  29. }
  30. std::string Goals::AbstractGoal::name() const //TODO: virtualize
  31. {
  32. std::string desc;
  33. switch(goalType)
  34. {
  35. case INVALID:
  36. return "INVALID";
  37. case WIN:
  38. return "WIN";
  39. case DO_NOT_LOSE:
  40. return "DO NOT LOOSE";
  41. case CONQUER:
  42. return "CONQUER";
  43. case BUILD:
  44. return "BUILD";
  45. case EXPLORE:
  46. desc = "EXPLORE";
  47. break;
  48. case GATHER_ARMY:
  49. desc = "GATHER ARMY";
  50. break;
  51. case BUY_ARMY:
  52. return "BUY ARMY";
  53. break;
  54. case BOOST_HERO:
  55. desc = "BOOST_HERO (unsupported)";
  56. break;
  57. case RECRUIT_HERO:
  58. return "RECRUIT HERO";
  59. case BUILD_STRUCTURE:
  60. return "BUILD STRUCTURE";
  61. case COLLECT_RES:
  62. desc = "COLLECT RESOURCE " + GameConstants::RESOURCE_NAMES[resID] + " (" + boost::lexical_cast<std::string>(value) + ")";
  63. break;
  64. case GATHER_TROOPS:
  65. desc = "GATHER TROOPS";
  66. break;
  67. case GET_OBJ:
  68. {
  69. auto obj = cb->getObjInstance(ObjectInstanceID(objid));
  70. if(obj)
  71. desc = "GET OBJ " + obj->getObjectName();
  72. }
  73. break;
  74. case FIND_OBJ:
  75. desc = "FIND OBJ " + boost::lexical_cast<std::string>(objid);
  76. break;
  77. case VISIT_HERO:
  78. {
  79. auto obj = cb->getObjInstance(ObjectInstanceID(objid));
  80. if(obj)
  81. desc = "VISIT HERO " + obj->getObjectName();
  82. }
  83. break;
  84. case GET_ART_TYPE:
  85. desc = "GET ARTIFACT OF TYPE " + VLC->arth->artifacts[aid]->Name();
  86. break;
  87. case ISSUE_COMMAND:
  88. return "ISSUE COMMAND (unsupported)";
  89. case VISIT_TILE:
  90. desc = "VISIT TILE " + tile.toString();
  91. break;
  92. case CLEAR_WAY_TO:
  93. desc = "CLEAR WAY TO " + tile.toString();
  94. break;
  95. case DIG_AT_TILE:
  96. desc = "DIG AT TILE " + tile.toString();
  97. break;
  98. default:
  99. return boost::lexical_cast<std::string>(goalType);
  100. }
  101. if(hero.get(true)) //FIXME: used to crash when we lost hero and failed goal
  102. desc += " (" + hero->name + ")";
  103. return desc;
  104. }
  105. //TODO: virtualize if code gets complex?
  106. bool Goals::AbstractGoal::operator==(AbstractGoal & g)
  107. {
  108. if(g.goalType != goalType)
  109. return false;
  110. if(g.isElementar != isElementar) //elementar goals fulfill long term non-elementar goals (VisitTile)
  111. return false;
  112. switch(goalType)
  113. {
  114. //no parameters
  115. case INVALID:
  116. case WIN:
  117. case DO_NOT_LOSE:
  118. case RECRUIT_HERO: //overloaded
  119. return true;
  120. break;
  121. //assigned to hero, no parameters
  122. case CONQUER:
  123. case EXPLORE:
  124. case BOOST_HERO:
  125. return g.hero.h == hero.h; //how comes HeroPtrs are equal for different heroes?
  126. break;
  127. case GATHER_ARMY: //actual value is indifferent
  128. return (g.hero.h == hero.h || town == g.town); //TODO: gather army for town maybe?
  129. break;
  130. //assigned hero and tile
  131. case VISIT_TILE:
  132. case CLEAR_WAY_TO:
  133. case DIG_AT_TILE:
  134. return (g.hero.h == hero.h && g.tile == tile);
  135. break;
  136. //assigned hero and object
  137. case GET_OBJ:
  138. case FIND_OBJ: //TODO: use subtype?
  139. case VISIT_HERO:
  140. case GET_ART_TYPE:
  141. return (g.hero.h == hero.h && g.objid == objid);
  142. break;
  143. case BUILD_STRUCTURE:
  144. return (town == g.town && bid == g.bid); //build specific structure in specific town
  145. break;
  146. //no check atm
  147. case COLLECT_RES:
  148. return (resID == g.resID); //every hero may collect resources
  149. break;
  150. case GATHER_TROOPS:
  151. case ISSUE_COMMAND:
  152. case BUILD: //TODO: should be decomposed to build specific structures
  153. default:
  154. return false;
  155. }
  156. }
  157. //TODO: find out why the following are not generated automatically on MVS?
  158. namespace Goals
  159. {
  160. template<>
  161. void CGoal<Win>::accept(VCAI * ai)
  162. {
  163. ai->tryRealize(static_cast<Win &>(*this));
  164. }
  165. template<>
  166. void CGoal<Build>::accept(VCAI * ai)
  167. {
  168. ai->tryRealize(static_cast<Build &>(*this));
  169. }
  170. template<>
  171. float CGoal<Win>::accept(FuzzyHelper * f)
  172. {
  173. return f->evaluate(static_cast<Win &>(*this));
  174. }
  175. template<>
  176. float CGoal<Build>::accept(FuzzyHelper * f)
  177. {
  178. return f->evaluate(static_cast<Build &>(*this));
  179. }
  180. bool TSubgoal::operator==(const TSubgoal & rhs) const
  181. {
  182. return *get() == *rhs.get(); //comparison for Goals is overloaded, so they don't need to be identical to match
  183. }
  184. bool BuyArmy::operator==(BuyArmy & g)
  185. {
  186. //if (hero && hero != g.hero)
  187. // return false;
  188. return town == g.town;
  189. }
  190. bool BuyArmy::fulfillsMe(TSubgoal goal)
  191. {
  192. //if (hero && hero != goal->hero)
  193. // return false;
  194. return town == goal->town && goal->value >= value; //can always buy more army
  195. }
  196. TSubgoal BuyArmy::whatToDoToAchieve()
  197. {
  198. //TODO: calculate the actual cost of units instead
  199. TResources price;
  200. price[Res::GOLD] = value * 0.4f; //some approximate value
  201. return ah->whatToDo(price, iAmElementar()); //buy right now or gather resources
  202. }
  203. std::string BuyArmy::completeMessage() const
  204. {
  205. return boost::format("Bought army of value %d in town of %s") % value, town->name;
  206. }
  207. }
  208. //TSubgoal AbstractGoal::whatToDoToAchieve()
  209. //{
  210. // logAi->debug("Decomposing goal of type %s",name());
  211. // return sptr (Goals::Explore());
  212. //}
  213. TSubgoal Win::whatToDoToAchieve()
  214. {
  215. auto toBool = [=](const EventCondition &)
  216. {
  217. // TODO: proper implementation
  218. // Right now even already fulfilled goals will be included into generated list
  219. // Proper check should test if event condition is already fulfilled
  220. // Easiest way to do this is to call CGameState::checkForVictory but this function should not be
  221. // used on client side or in AI code
  222. return false;
  223. };
  224. std::vector<EventCondition> goals;
  225. for(const TriggeredEvent & event : cb->getMapHeader()->triggeredEvents)
  226. {
  227. //TODO: try to eliminate human player(s) using loss conditions that have isHuman element
  228. if(event.effect.type == EventEffect::VICTORY)
  229. {
  230. boost::range::copy(event.trigger.getFulfillmentCandidates(toBool), std::back_inserter(goals));
  231. }
  232. }
  233. //TODO: instead of returning first encountered goal AI should generate list of possible subgoals
  234. for(const EventCondition & goal : goals)
  235. {
  236. switch(goal.condition)
  237. {
  238. case EventCondition::HAVE_ARTIFACT:
  239. return sptr(Goals::GetArtOfType(goal.objectType));
  240. case EventCondition::DESTROY:
  241. {
  242. if(goal.object)
  243. {
  244. auto obj = cb->getObj(goal.object->id);
  245. if(obj)
  246. if(obj->getOwner() == ai->playerID) //we can't capture our own object
  247. return sptr(Goals::Conquer());
  248. return sptr(Goals::GetObj(goal.object->id.getNum()));
  249. }
  250. else
  251. {
  252. // TODO: destroy all objects of type goal.objectType
  253. // This situation represents "kill all creatures" condition from H3
  254. break;
  255. }
  256. }
  257. case EventCondition::HAVE_BUILDING:
  258. {
  259. // TODO build other buildings apart from Grail
  260. // goal.objectType = buidingID to build
  261. // goal.object = optional, town in which building should be built
  262. // Represents "Improve town" condition from H3 (but unlike H3 it consists from 2 separate conditions)
  263. if(goal.objectType == BuildingID::GRAIL)
  264. {
  265. if(auto h = ai->getHeroWithGrail())
  266. {
  267. //hero is in a town that can host Grail
  268. if(h->visitedTown && !vstd::contains(h->visitedTown->forbiddenBuildings, BuildingID::GRAIL))
  269. {
  270. const CGTownInstance * t = h->visitedTown;
  271. return sptr(Goals::BuildThis(BuildingID::GRAIL, t).setpriority(10));
  272. }
  273. else
  274. {
  275. auto towns = cb->getTownsInfo();
  276. towns.erase(boost::remove_if(towns,
  277. [](const CGTownInstance * t) -> bool
  278. {
  279. return vstd::contains(t->forbiddenBuildings, BuildingID::GRAIL);
  280. }),
  281. towns.end());
  282. boost::sort(towns, CDistanceSorter(h.get()));
  283. if(towns.size())
  284. {
  285. return sptr(Goals::VisitTile(towns.front()->visitablePos()).sethero(h));
  286. }
  287. }
  288. }
  289. double ratio = 0;
  290. // maybe make this check a bit more complex? For example:
  291. // 0.75 -> dig randomly within 3 tiles radius
  292. // 0.85 -> radius now 2 tiles
  293. // 0.95 -> 1 tile radius, position is fully known
  294. // AFAIK H3 AI does something like this
  295. int3 grailPos = cb->getGrailPos(&ratio);
  296. if(ratio > 0.99)
  297. {
  298. return sptr(Goals::DigAtTile(grailPos));
  299. } //TODO: use FIND_OBJ
  300. else if(const CGObjectInstance * obj = ai->getUnvisitedObj(objWithID<Obj::OBELISK>)) //there are unvisited Obelisks
  301. return sptr(Goals::GetObj(obj->id.getNum()));
  302. else
  303. return sptr(Goals::Explore());
  304. }
  305. break;
  306. }
  307. case EventCondition::CONTROL:
  308. {
  309. if(goal.object)
  310. {
  311. return sptr(Goals::GetObj(goal.object->id.getNum()));
  312. }
  313. else
  314. {
  315. //TODO: control all objects of type "goal.objectType"
  316. // Represents H3 condition "Flag all mines"
  317. break;
  318. }
  319. }
  320. case EventCondition::HAVE_RESOURCES:
  321. //TODO mines? piles? marketplace?
  322. //save?
  323. return sptr(Goals::CollectRes(static_cast<Res::ERes>(goal.objectType), goal.value));
  324. case EventCondition::HAVE_CREATURES:
  325. return sptr(Goals::GatherTroops(goal.objectType, goal.value));
  326. case EventCondition::TRANSPORT:
  327. {
  328. //TODO. merge with bring Grail to town? So AI will first dig grail, then transport it using this goal and builds it
  329. // Represents "transport artifact" condition:
  330. // goal.objectType = type of artifact
  331. // goal.object = destination-town where artifact should be transported
  332. break;
  333. }
  334. case EventCondition::STANDARD_WIN:
  335. return sptr(Goals::Conquer());
  336. // Conditions that likely don't need any implementation
  337. case EventCondition::DAYS_PASSED:
  338. break; // goal.value = number of days for condition to trigger
  339. case EventCondition::DAYS_WITHOUT_TOWN:
  340. break; // goal.value = number of days to trigger this
  341. case EventCondition::IS_HUMAN:
  342. break; // Should be only used in calculation of candidates (see toBool lambda)
  343. case EventCondition::CONST_VALUE:
  344. break;
  345. case EventCondition::HAVE_0:
  346. case EventCondition::HAVE_BUILDING_0:
  347. case EventCondition::DESTROY_0:
  348. //TODO: support new condition format
  349. return sptr(Goals::Conquer());
  350. default:
  351. assert(0);
  352. }
  353. }
  354. return sptr(Goals::Invalid());
  355. }
  356. TSubgoal FindObj::whatToDoToAchieve()
  357. {
  358. const CGObjectInstance * o = nullptr;
  359. if(resID > -1) //specified
  360. {
  361. for(const CGObjectInstance * obj : ai->visitableObjs)
  362. {
  363. if(obj->ID == objid && obj->subID == resID)
  364. {
  365. o = obj;
  366. break; //TODO: consider multiple objects and choose best
  367. }
  368. }
  369. }
  370. else
  371. {
  372. for(const CGObjectInstance * obj : ai->visitableObjs)
  373. {
  374. if(obj->ID == objid)
  375. {
  376. o = obj;
  377. break; //TODO: consider multiple objects and choose best
  378. }
  379. }
  380. }
  381. if(o && ai->isAccessible(o->pos)) //we don't use isAccessibleForHero as we don't know which hero it is
  382. return sptr(Goals::GetObj(o->id.getNum()));
  383. else
  384. return sptr(Goals::Explore());
  385. }
  386. bool Goals::FindObj::fulfillsMe(TSubgoal goal)
  387. {
  388. if (goal->goalType == Goals::VISIT_TILE) //visiting tile visits object at same time
  389. {
  390. if (!hero || hero == goal->hero)
  391. for (auto obj : cb->getVisitableObjs(goal->tile)) //check if any object on that tile matches criteria
  392. if (obj->visitablePos() == goal->tile) //object could be removed
  393. if (obj->ID == objid && obj->subID == resID) //same type and subtype
  394. return true;
  395. }
  396. return false;
  397. }
  398. std::string GetObj::completeMessage() const
  399. {
  400. return "hero " + hero.get()->name + " captured Object ID = " + boost::lexical_cast<std::string>(objid);
  401. }
  402. TSubgoal GetObj::whatToDoToAchieve()
  403. {
  404. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(objid));
  405. if(!obj)
  406. return sptr(Goals::Explore());
  407. if(obj->tempOwner == ai->playerID) //we can't capture our own object -> move to Win codition
  408. throw cannotFulfillGoalException("Cannot capture my own object " + obj->getObjectName());
  409. int3 pos = obj->visitablePos();
  410. if(hero)
  411. {
  412. if(ai->isAccessibleForHero(pos, hero))
  413. return sptr(Goals::VisitTile(pos).sethero(hero));
  414. }
  415. else
  416. {
  417. for(auto h : cb->getHeroesInfo())
  418. {
  419. if(ai->isAccessibleForHero(pos, h))
  420. return sptr(Goals::VisitTile(pos).sethero(h)); //we must visit object with same hero, if any
  421. }
  422. }
  423. return sptr(Goals::ClearWayTo(pos).sethero(hero));
  424. }
  425. bool GetObj::fulfillsMe(TSubgoal goal)
  426. {
  427. if(goal->goalType == Goals::VISIT_TILE) //visiting tile visits object at same time
  428. {
  429. if (!hero || hero == goal->hero)
  430. {
  431. auto obj = cb->getObj(ObjectInstanceID(objid));
  432. if (obj && obj->visitablePos() == goal->tile) //object could be removed
  433. return true;
  434. }
  435. }
  436. return false;
  437. }
  438. std::string VisitHero::completeMessage() const
  439. {
  440. return "hero " + hero.get()->name + " visited hero " + boost::lexical_cast<std::string>(objid);
  441. }
  442. TSubgoal VisitHero::whatToDoToAchieve()
  443. {
  444. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(objid));
  445. if(!obj)
  446. return sptr(Goals::Explore());
  447. int3 pos = obj->visitablePos();
  448. if(hero && ai->isAccessibleForHero(pos, hero, true) && isSafeToVisit(hero, pos)) //enemy heroes can get reinforcements
  449. {
  450. if(hero->pos == pos)
  451. logAi->error("Hero %s tries to visit himself.", hero.name);
  452. else
  453. {
  454. //can't use VISIT_TILE here as tile appears blocked by target hero
  455. //FIXME: elementar goal should not be abstract
  456. return sptr(Goals::VisitHero(objid).sethero(hero).settile(pos).setisElementar(true));
  457. }
  458. }
  459. return sptr(Goals::Invalid());
  460. }
  461. bool VisitHero::fulfillsMe(TSubgoal goal)
  462. {
  463. //TODO: VisitObj shoudl not be used for heroes, but...
  464. if(goal->goalType == Goals::VISIT_TILE)
  465. {
  466. auto obj = cb->getObj(ObjectInstanceID(objid));
  467. if (!obj)
  468. {
  469. logAi->error("Hero %s: VisitHero::fulfillsMe at %s: object %d not found", hero.name, goal->tile.toString(), objid);
  470. return false;
  471. }
  472. return obj->visitablePos() == goal->tile;
  473. }
  474. return false;
  475. }
  476. TSubgoal GetArtOfType::whatToDoToAchieve()
  477. {
  478. TSubgoal alternativeWay = CGoal::lookForArtSmart(aid); //TODO: use
  479. if(alternativeWay->invalid())
  480. return sptr(Goals::FindObj(Obj::ARTIFACT, aid));
  481. return sptr(Goals::Invalid());
  482. }
  483. TSubgoal ClearWayTo::whatToDoToAchieve()
  484. {
  485. assert(cb->isInTheMap(tile)); //set tile
  486. if(!cb->isVisible(tile))
  487. {
  488. logAi->error("Clear way should be used with visible tiles!");
  489. return sptr(Goals::Explore());
  490. }
  491. return (fh->chooseSolution(getAllPossibleSubgoals()));
  492. }
  493. bool Goals::ClearWayTo::fulfillsMe(TSubgoal goal)
  494. {
  495. if (goal->goalType == Goals::VISIT_TILE)
  496. {
  497. if (!hero || hero == goal->hero)
  498. return tile == goal->tile;
  499. }
  500. return false;
  501. }
  502. TGoalVec ClearWayTo::getAllPossibleSubgoals()
  503. {
  504. TGoalVec ret;
  505. std::vector<const CGHeroInstance *> heroes;
  506. if(hero)
  507. heroes.push_back(hero.h);
  508. else
  509. heroes = cb->getHeroesInfo();
  510. for(auto h : heroes)
  511. {
  512. //TODO: handle clearing way to allied heroes that are blocked
  513. //if ((hero && hero->visitablePos() == tile && hero == *h) || //we can't free the way ourselves
  514. // h->visitablePos() == tile) //we are already on that tile! what does it mean?
  515. // continue;
  516. //if our hero is trapped, make sure we request clearing the way from OUR perspective
  517. auto sm = ai->getCachedSectorMap(h);
  518. int3 tileToHit = sm->firstTileToGet(h, tile);
  519. if(!tileToHit.valid())
  520. continue;
  521. if(isBlockedBorderGate(tileToHit))
  522. {
  523. //FIXME: this way we'll not visit gate and activate quest :?
  524. ret.push_back(sptr(Goals::FindObj(Obj::KEYMASTER, cb->getTile(tileToHit)->visitableObjects.back()->subID)));
  525. }
  526. auto topObj = cb->getTopObj(tileToHit);
  527. if(topObj)
  528. {
  529. if(vstd::contains(ai->reservedObjs, topObj) && !vstd::contains(ai->reservedHeroesMap[h], topObj))
  530. {
  531. throw goalFulfilledException(sptr(Goals::ClearWayTo(tile, h)));
  532. continue; //do not capure object reserved by other hero
  533. }
  534. if(topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES)
  535. {
  536. if(topObj != hero.get(true)) //the hero we want to free
  537. logAi->error("%s stands in the way of %s", topObj->getObjectName(), h->getObjectName());
  538. }
  539. if(topObj->ID == Obj::QUEST_GUARD || topObj->ID == Obj::BORDERGUARD)
  540. {
  541. if(shouldVisit(h, topObj))
  542. {
  543. //do NOT use VISIT_TILE, as tile with quets guard can't be visited
  544. ret.push_back(sptr(Goals::GetObj(topObj->id.getNum()).sethero(h)));
  545. continue; //do not try to visit tile or gather army
  546. }
  547. else
  548. {
  549. //TODO: we should be able to return apriopriate quest here (VCAI::striveToQuest)
  550. logAi->debug("Quest guard blocks the way to %s", tile.toString());
  551. continue; //do not access quets guard if we can't complete the quest
  552. }
  553. }
  554. }
  555. if(isSafeToVisit(h, tileToHit)) //this makes sense only if tile is guarded, but there i no quest object
  556. {
  557. ret.push_back(sptr(Goals::VisitTile(tileToHit).sethero(h)));
  558. }
  559. else
  560. {
  561. ret.push_back(sptr(Goals::GatherArmy(evaluateDanger(tileToHit, h) * SAFE_ATTACK_CONSTANT).
  562. sethero(h).setisAbstract(true)));
  563. }
  564. }
  565. if(ai->canRecruitAnyHero())
  566. ret.push_back(sptr(Goals::RecruitHero()));
  567. if(ret.empty())
  568. {
  569. logAi->warn("There is no known way to clear the way to tile %s", tile.toString());
  570. throw goalFulfilledException(sptr(Goals::ClearWayTo(tile))); //make sure asigned hero gets unlocked
  571. }
  572. return ret;
  573. }
  574. std::string Explore::completeMessage() const
  575. {
  576. return "Hero " + hero.get()->name + " completed exploration";
  577. }
  578. TSubgoal Explore::whatToDoToAchieve()
  579. {
  580. auto ret = fh->chooseSolution(getAllPossibleSubgoals());
  581. if(hero) //use best step for this hero
  582. {
  583. return ret;
  584. }
  585. else
  586. {
  587. if(ret->hero.get(true))
  588. return sptr(sethero(ret->hero.h).setisAbstract(true)); //choose this hero and then continue with him
  589. else
  590. return ret; //other solutions, like buying hero from tavern
  591. }
  592. }
  593. TGoalVec Explore::getAllPossibleSubgoals()
  594. {
  595. TGoalVec ret;
  596. std::vector<const CGHeroInstance *> heroes;
  597. if(hero)
  598. {
  599. heroes.push_back(hero.h);
  600. }
  601. else
  602. {
  603. //heroes = ai->getUnblockedHeroes();
  604. heroes = cb->getHeroesInfo();
  605. vstd::erase_if(heroes, [](const HeroPtr h)
  606. {
  607. if(ai->getGoal(h)->goalType == Goals::EXPLORE) //do not reassign hero who is already explorer
  608. return true;
  609. if(!ai->isAbleToExplore(h))
  610. return true;
  611. return !h->movement; //saves time, immobile heroes are useless anyway
  612. });
  613. }
  614. //try to use buildings that uncover map
  615. std::vector<const CGObjectInstance *> objs;
  616. for(auto obj : ai->visitableObjs)
  617. {
  618. if(!vstd::contains(ai->alreadyVisited, obj))
  619. {
  620. switch(obj->ID.num)
  621. {
  622. case Obj::REDWOOD_OBSERVATORY:
  623. case Obj::PILLAR_OF_FIRE:
  624. case Obj::CARTOGRAPHER:
  625. objs.push_back(obj);
  626. break;
  627. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  628. case Obj::MONOLITH_TWO_WAY:
  629. case Obj::SUBTERRANEAN_GATE:
  630. auto tObj = dynamic_cast<const CGTeleport *>(obj);
  631. assert(ai->knownTeleportChannels.find(tObj->channel) != ai->knownTeleportChannels.end());
  632. if(TeleportChannel::IMPASSABLE != ai->knownTeleportChannels[tObj->channel]->passability)
  633. objs.push_back(obj);
  634. break;
  635. }
  636. }
  637. else
  638. {
  639. switch(obj->ID.num)
  640. {
  641. case Obj::MONOLITH_TWO_WAY:
  642. case Obj::SUBTERRANEAN_GATE:
  643. auto tObj = dynamic_cast<const CGTeleport *>(obj);
  644. if(TeleportChannel::IMPASSABLE == ai->knownTeleportChannels[tObj->channel]->passability)
  645. break;
  646. for(auto exit : ai->knownTeleportChannels[tObj->channel]->exits)
  647. {
  648. if(!cb->getObj(exit))
  649. { // Always attempt to visit two-way teleports if one of channel exits is not visible
  650. objs.push_back(obj);
  651. break;
  652. }
  653. }
  654. break;
  655. }
  656. }
  657. }
  658. auto primaryHero = ai->primaryHero().h;
  659. for(auto h : heroes)
  660. {
  661. auto sm = ai->getCachedSectorMap(h);
  662. for(auto obj : objs) //double loop, performance risk?
  663. {
  664. auto t = sm->firstTileToGet(h, obj->visitablePos()); //we assume that no more than one tile on the way is guarded
  665. if(ai->isTileNotReserved(h, t))
  666. ret.push_back(sptr(Goals::ClearWayTo(obj->visitablePos(), h).setisAbstract(true)));
  667. }
  668. int3 t = whereToExplore(h);
  669. if(t.valid())
  670. {
  671. ret.push_back(sptr(Goals::VisitTile(t).sethero(h)));
  672. }
  673. else
  674. {
  675. //FIXME: possible issues when gathering army to break
  676. if(hero.h == h || //exporation is assigned to this hero
  677. (!hero && h == primaryHero)) //not assigned to specific hero, let our main hero do the job
  678. {
  679. t = ai->explorationDesperate(h); //check this only ONCE, high cost
  680. if (t.valid()) //don't waste time if we are completely blocked
  681. {
  682. ret.push_back(sptr(Goals::ClearWayTo(t, h).setisAbstract(true)));
  683. continue;
  684. }
  685. }
  686. ai->markHeroUnableToExplore(h); //there is no freely accessible tile, do not poll this hero anymore
  687. }
  688. }
  689. //we either don't have hero yet or none of heroes can explore
  690. if((!hero || ret.empty()) && ai->canRecruitAnyHero())
  691. ret.push_back(sptr(Goals::RecruitHero()));
  692. if(ret.empty())
  693. {
  694. throw goalFulfilledException(sptr(Goals::Explore().sethero(hero)));
  695. }
  696. //throw cannotFulfillGoalException("Cannot explore - no possible ways found!");
  697. return ret;
  698. }
  699. bool Explore::fulfillsMe(TSubgoal goal)
  700. {
  701. if(goal->goalType == Goals::EXPLORE)
  702. {
  703. if(goal->hero)
  704. return hero == goal->hero;
  705. else
  706. return true; //cancel ALL exploration
  707. }
  708. return false;
  709. }
  710. TSubgoal RecruitHero::whatToDoToAchieve()
  711. {
  712. const CGTownInstance * t = ai->findTownWithTavern();
  713. if(!t)
  714. return sptr(Goals::BuildThis(BuildingID::TAVERN).setpriority(2));
  715. TResources res;
  716. res[Res::GOLD] = GameConstants::HERO_GOLD_COST;
  717. return ah->whatToDo(res, iAmElementar()); //either buy immediately, or collect res
  718. }
  719. bool Goals::RecruitHero::operator==(RecruitHero & g)
  720. {
  721. //TODO: check town and hero
  722. return true; //for now, recruiting any hero will do
  723. }
  724. std::string VisitTile::completeMessage() const
  725. {
  726. return "Hero " + hero.get()->name + " visited tile " + tile.toString();
  727. }
  728. TSubgoal VisitTile::whatToDoToAchieve()
  729. {
  730. auto ret = fh->chooseSolution(getAllPossibleSubgoals());
  731. if(ret->hero)
  732. {
  733. if(isSafeToVisit(ret->hero, tile) && ai->isAccessibleForHero(tile, ret->hero))
  734. {
  735. if(cb->getTile(tile)->topVisitableId().num == Obj::TOWN) //if target is town, fuzzy system will use additional "estimatedReward" variable to increase priority a bit
  736. ret->objid = Obj::TOWN; //TODO: move to getObj eventually and add appropiate logic there
  737. ret->setisElementar(true);
  738. return ret;
  739. }
  740. else
  741. {
  742. return sptr(Goals::GatherArmy(evaluateDanger(tile, *ret->hero) * SAFE_ATTACK_CONSTANT)
  743. .sethero(ret->hero).setisAbstract(true));
  744. }
  745. }
  746. return ret;
  747. }
  748. TGoalVec VisitTile::getAllPossibleSubgoals()
  749. {
  750. assert(cb->isInTheMap(tile));
  751. TGoalVec ret;
  752. if(!cb->isVisible(tile))
  753. ret.push_back(sptr(Goals::Explore())); //what sense does it make?
  754. else
  755. {
  756. std::vector<const CGHeroInstance *> heroes;
  757. if(hero)
  758. heroes.push_back(hero.h); //use assigned hero if any
  759. else
  760. heroes = cb->getHeroesInfo(); //use most convenient hero
  761. for(auto h : heroes)
  762. {
  763. if(ai->isAccessibleForHero(tile, h))
  764. ret.push_back(sptr(Goals::VisitTile(tile).sethero(h)));
  765. }
  766. if(ai->canRecruitAnyHero())
  767. ret.push_back(sptr(Goals::RecruitHero()));
  768. }
  769. if(ret.empty())
  770. {
  771. auto obj = vstd::frontOrNull(cb->getVisitableObjs(tile));
  772. if(obj && obj->ID == Obj::HERO && obj->tempOwner == ai->playerID) //our own hero stands on that tile
  773. {
  774. if(hero.get(true) && hero->id == obj->id) //if it's assigned hero, visit tile. If it's different hero, we can't visit tile now
  775. ret.push_back(sptr(Goals::VisitTile(tile).sethero(dynamic_cast<const CGHeroInstance *>(obj)).setisElementar(true)));
  776. else
  777. throw cannotFulfillGoalException("Tile is already occupied by another hero "); //FIXME: we should give up this tile earlier
  778. }
  779. else
  780. ret.push_back(sptr(Goals::ClearWayTo(tile)));
  781. }
  782. //important - at least one sub-goal must handle case which is impossible to fulfill (unreachable tile)
  783. return ret;
  784. }
  785. TSubgoal DigAtTile::whatToDoToAchieve()
  786. {
  787. const CGObjectInstance * firstObj = vstd::frontOrNull(cb->getVisitableObjs(tile));
  788. if(firstObj && firstObj->ID == Obj::HERO && firstObj->tempOwner == ai->playerID) //we have hero at dest
  789. {
  790. const CGHeroInstance * h = dynamic_cast<const CGHeroInstance *>(firstObj);
  791. sethero(h).setisElementar(true);
  792. return sptr(*this);
  793. }
  794. return sptr(Goals::VisitTile(tile));
  795. }
  796. TSubgoal BuildThis::whatToDoToAchieve()
  797. {
  798. auto b = BuildingID(bid);
  799. // find town if not set
  800. if (!town && hero)
  801. town = hero->visitedTown;
  802. if (!town)
  803. {
  804. for (const CGTownInstance * t : cb->getTownsInfo())
  805. {
  806. switch (cb->canBuildStructure(town, b))
  807. {
  808. case EBuildingState::ALLOWED:
  809. town = t;
  810. break; //TODO: look for prerequisites? this is not our reponsibility
  811. default:
  812. continue;
  813. }
  814. }
  815. }
  816. if (town) //we have specific town to build this
  817. {
  818. auto res = town->town->buildings.at(BuildingID(bid))->resources;
  819. return ah->whatToDo(res, iAmElementar()); //realize immediately or gather resources
  820. }
  821. else
  822. throw cannotFulfillGoalException("Cannot find town to build this");
  823. }
  824. TGoalVec Goals::CollectRes::getAllPossibleSubgoals()
  825. {
  826. TGoalVec ret;
  827. auto givesResource = [this](const CGObjectInstance * obj) -> bool
  828. {
  829. //TODO: move this logic to object side
  830. //TODO: remember mithril exists
  831. //TODO: water objects
  832. //TODO: Creature banks
  833. //return false first from once-visitable, before checking if they were even visited
  834. switch (obj->ID.num)
  835. {
  836. case Obj::TREASURE_CHEST:
  837. return resID == Res::GOLD;
  838. break;
  839. case Obj::RESOURCE:
  840. return obj->subID == resID;
  841. break;
  842. case Obj::MINE:
  843. return (obj->subID == resID &&
  844. (cb->getPlayerRelations(obj->tempOwner, ai->playerID) == PlayerRelations::ENEMIES)); //don't capture our mines
  845. break;
  846. case Obj::CAMPFIRE:
  847. return true; //contains all resources
  848. break;
  849. case Obj::WINDMILL:
  850. switch (resID)
  851. {
  852. case Res::GOLD:
  853. case Res::WOOD:
  854. return false;
  855. }
  856. break;
  857. case Obj::WATER_WHEEL:
  858. if (resID != Res::GOLD)
  859. return false;
  860. break;
  861. case Obj::MYSTICAL_GARDEN:
  862. if ((resID != Res::GOLD) && (resID != Res::GEMS))
  863. return false;
  864. break;
  865. case Obj::LEAN_TO:
  866. case Obj::WAGON:
  867. if (resID != Res::GOLD)
  868. return false;
  869. break;
  870. default:
  871. return false;
  872. break;
  873. }
  874. return !vstd::contains(ai->alreadyVisited, obj); //for weekly / once visitable
  875. };
  876. std::vector<const CGObjectInstance *> objs;
  877. for (auto obj : ai->visitableObjs)
  878. {
  879. if (givesResource(obj))
  880. objs.push_back(obj);
  881. }
  882. for (auto h : cb->getHeroesInfo())
  883. {
  884. auto sm = ai->getCachedSectorMap(h);
  885. std::vector<const CGObjectInstance *> ourObjs(objs); //copy common objects
  886. for (auto obj : ai->reservedHeroesMap[h]) //add objects reserved by this hero
  887. {
  888. if (givesResource(obj))
  889. ourObjs.push_back(obj);
  890. }
  891. for (auto obj : ourObjs)
  892. {
  893. int3 dest = obj->visitablePos();
  894. auto t = sm->firstTileToGet(h, dest); //we assume that no more than one tile on the way is guarded
  895. if (t.valid()) //we know any path at all
  896. {
  897. if (ai->isTileNotReserved(h, t)) //no other hero wants to conquer that tile
  898. {
  899. if (isSafeToVisit(h, dest))
  900. {
  901. if (dest != t) //there is something blocking our way
  902. ret.push_back(sptr(Goals::ClearWayTo(dest, h).setisAbstract(true)));
  903. else
  904. ret.push_back(sptr(Goals::VisitTile(dest).sethero(h).setisAbstract(true)));
  905. }
  906. else //we need to get army in order to pick that object
  907. ret.push_back(sptr(Goals::GatherArmy(evaluateDanger(dest, h) * SAFE_ATTACK_CONSTANT).sethero(h).setisAbstract(true)));
  908. }
  909. }
  910. }
  911. }
  912. return ret;
  913. }
  914. TSubgoal CollectRes::whatToDoToAchieve()
  915. {
  916. auto goals = getAllPossibleSubgoals();
  917. auto trade = whatToDoToTrade();
  918. if (!trade->invalid())
  919. goals.push_back(trade);
  920. if (goals.empty())
  921. return sptr(Goals::Explore()); //we can always do that
  922. else
  923. return fh->chooseSolution(goals); //TODO: evaluate trading
  924. }
  925. TSubgoal Goals::CollectRes::whatToDoToTrade()
  926. {
  927. std::vector<const IMarket *> markets;
  928. std::vector<const CGObjectInstance *> visObjs;
  929. ai->retrieveVisitableObjs(visObjs, true);
  930. for (const CGObjectInstance * obj : visObjs)
  931. {
  932. if (const IMarket * m = IMarket::castFrom(obj, false))
  933. {
  934. if (obj->ID == Obj::TOWN && obj->tempOwner == ai->playerID && m->allowsTrade(EMarketMode::RESOURCE_RESOURCE))
  935. markets.push_back(m);
  936. else if (obj->ID == Obj::TRADING_POST)
  937. markets.push_back(m);
  938. }
  939. }
  940. boost::sort(markets, [](const IMarket * m1, const IMarket * m2) -> bool
  941. {
  942. return m1->getMarketEfficiency() < m2->getMarketEfficiency();
  943. });
  944. markets.erase(boost::remove_if(markets, [](const IMarket * market) -> bool
  945. {
  946. if (!(market->o->ID == Obj::TOWN && market->o->tempOwner == ai->playerID))
  947. {
  948. if (!ai->isAccessible(market->o->visitablePos()))
  949. return true;
  950. }
  951. return false;
  952. }), markets.end());
  953. if (!markets.size())
  954. {
  955. for (const CGTownInstance * t : cb->getTownsInfo())
  956. {
  957. if (cb->canBuildStructure(t, BuildingID::MARKETPLACE) == EBuildingState::ALLOWED)
  958. return sptr(Goals::BuildThis(BuildingID::MARKETPLACE, t).setpriority(2));
  959. }
  960. }
  961. else
  962. {
  963. const IMarket * m = markets.back();
  964. //attempt trade at back (best prices)
  965. int howManyCanWeBuy = 0;
  966. for (Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
  967. {
  968. if (i == resID)
  969. continue;
  970. int toGive = -1, toReceive = -1;
  971. m->getOffer(i, resID, toGive, toReceive, EMarketMode::RESOURCE_RESOURCE);
  972. assert(toGive > 0 && toReceive > 0);
  973. howManyCanWeBuy += toReceive * (cb->getResourceAmount(i) / toGive);
  974. }
  975. if (howManyCanWeBuy >= value)
  976. {
  977. auto backObj = cb->getTopObj(m->o->visitablePos()); //it'll be a hero if we have one there; otherwise marketplace
  978. assert(backObj);
  979. auto objid = m->o->id.getNum();
  980. if (backObj->tempOwner != ai->playerID) //top object not owned
  981. {
  982. return sptr(Goals::GetObj(objid)); //just go there
  983. }
  984. else //either it's our town, or we have hero there
  985. {
  986. return sptr(setobjid(objid).setisElementar(true));
  987. }
  988. }
  989. }
  990. return sptr(Goals::Invalid()); //cannot trade
  991. //TODO: separate goal to execute trade?
  992. //return sptr(setisElementar(true)); //not sure why we are here
  993. }
  994. bool CollectRes::fulfillsMe(TSubgoal goal)
  995. {
  996. if (goal->resID == resID)
  997. if (goal->value >= value)
  998. return true;
  999. return false;
  1000. }
  1001. TSubgoal GatherTroops::whatToDoToAchieve()
  1002. {
  1003. std::vector<const CGDwelling *> dwellings;
  1004. for(const CGTownInstance * t : cb->getTownsInfo())
  1005. {
  1006. auto creature = VLC->creh->creatures[objid];
  1007. if(t->subID == creature->faction) //TODO: how to force AI to build unupgraded creatures? :O
  1008. {
  1009. auto creatures = vstd::tryAt(t->town->creatures, creature->level - 1);
  1010. if(!creatures)
  1011. continue;
  1012. int upgradeNumber = vstd::find_pos(*creatures, creature->idNumber);
  1013. if(upgradeNumber < 0)
  1014. continue;
  1015. BuildingID bid(BuildingID::DWELL_FIRST + creature->level - 1 + upgradeNumber * GameConstants::CREATURES_PER_TOWN);
  1016. if(t->hasBuilt(bid)) //this assumes only creatures with dwellings are assigned to faction
  1017. {
  1018. dwellings.push_back(t);
  1019. }
  1020. else
  1021. {
  1022. return sptr(Goals::BuildThis(bid, t).setpriority(priority));
  1023. }
  1024. }
  1025. }
  1026. for(auto obj : ai->visitableObjs)
  1027. {
  1028. if(obj->ID != Obj::CREATURE_GENERATOR1) //TODO: what with other creature generators?
  1029. continue;
  1030. auto d = dynamic_cast<const CGDwelling *>(obj);
  1031. for(auto creature : d->creatures)
  1032. {
  1033. if(creature.first) //there are more than 0 creatures avaliabe
  1034. {
  1035. for(auto type : creature.second)
  1036. {
  1037. if(type == objid && ah->freeResources().canAfford(VLC->creh->creatures[type]->cost))
  1038. dwellings.push_back(d);
  1039. }
  1040. }
  1041. }
  1042. }
  1043. if(dwellings.size())
  1044. {
  1045. typedef std::map<const CGHeroInstance *, const CGDwelling *> TDwellMap;
  1046. // sorted helper
  1047. auto comparator = [](const TDwellMap::value_type & a, const TDwellMap::value_type & b) -> bool
  1048. {
  1049. const CGPathNode * ln = ai->myCb->getPathsInfo(a.first)->getPathInfo(a.second->visitablePos());
  1050. const CGPathNode * rn = ai->myCb->getPathsInfo(b.first)->getPathInfo(b.second->visitablePos());
  1051. if(ln->turns != rn->turns)
  1052. return ln->turns < rn->turns;
  1053. return (ln->moveRemains > rn->moveRemains);
  1054. };
  1055. // for all owned heroes generate map <hero -> nearest dwelling>
  1056. TDwellMap nearestDwellings;
  1057. for(const CGHeroInstance * hero : cb->getHeroesInfo(true))
  1058. {
  1059. nearestDwellings[hero] = *boost::range::min_element(dwellings, CDistanceSorter(hero));
  1060. }
  1061. if(nearestDwellings.size())
  1062. {
  1063. // find hero who is nearest to a dwelling
  1064. const CGDwelling * nearest = boost::range::min_element(nearestDwellings, comparator)->second;
  1065. if(!nearest)
  1066. throw cannotFulfillGoalException("Cannot find nearest dwelling!");
  1067. return sptr(Goals::GetObj(nearest->id.getNum()));
  1068. }
  1069. else
  1070. return sptr(Goals::Explore());
  1071. }
  1072. else
  1073. {
  1074. return sptr(Goals::Explore());
  1075. }
  1076. //TODO: exchange troops between heroes
  1077. }
  1078. bool Goals::GatherTroops::fulfillsMe(TSubgoal goal)
  1079. {
  1080. if (!hero || hero == goal->hero) //we got army for desired hero or any hero
  1081. if (goal->objid == objid) //same creature type //TODO: consider upgrades?
  1082. if (goal->value >= value) //notify every time we get resources?
  1083. return true;
  1084. return false;
  1085. }
  1086. TSubgoal Conquer::whatToDoToAchieve()
  1087. {
  1088. return fh->chooseSolution(getAllPossibleSubgoals());
  1089. }
  1090. TGoalVec Conquer::getAllPossibleSubgoals()
  1091. {
  1092. TGoalVec ret;
  1093. auto conquerable = [](const CGObjectInstance * obj) -> bool
  1094. {
  1095. if(cb->getPlayerRelations(ai->playerID, obj->tempOwner) == PlayerRelations::ENEMIES)
  1096. {
  1097. switch(obj->ID.num)
  1098. {
  1099. case Obj::TOWN:
  1100. case Obj::HERO:
  1101. case Obj::CREATURE_GENERATOR1:
  1102. case Obj::MINE: //TODO: check ai->knownSubterraneanGates
  1103. return true;
  1104. }
  1105. }
  1106. return false;
  1107. };
  1108. std::vector<const CGObjectInstance *> objs;
  1109. for(auto obj : ai->visitableObjs)
  1110. {
  1111. if(conquerable(obj))
  1112. objs.push_back(obj);
  1113. }
  1114. for(auto h : cb->getHeroesInfo())
  1115. {
  1116. auto sm = ai->getCachedSectorMap(h);
  1117. std::vector<const CGObjectInstance *> ourObjs(objs); //copy common objects
  1118. for(auto obj : ai->reservedHeroesMap[h]) //add objects reserved by this hero
  1119. {
  1120. if(conquerable(obj))
  1121. ourObjs.push_back(obj);
  1122. }
  1123. for(auto obj : ourObjs)
  1124. {
  1125. int3 dest = obj->visitablePos();
  1126. auto t = sm->firstTileToGet(h, dest); //we assume that no more than one tile on the way is guarded
  1127. if(t.valid()) //we know any path at all
  1128. {
  1129. if(ai->isTileNotReserved(h, t)) //no other hero wants to conquer that tile
  1130. {
  1131. if(isSafeToVisit(h, dest))
  1132. {
  1133. if(dest != t) //there is something blocking our way
  1134. ret.push_back(sptr(Goals::ClearWayTo(dest, h).setisAbstract(true)));
  1135. else
  1136. {
  1137. if(obj->ID.num == Obj::HERO) //enemy hero may move to other position
  1138. {
  1139. ret.push_back(sptr(Goals::VisitHero(obj->id.getNum()).sethero(h).setisAbstract(true)));
  1140. }
  1141. else //just visit that tile
  1142. {
  1143. if(obj->ID.num == Obj::TOWN)
  1144. //if target is town, fuzzy system will use additional "estimatedReward" variable to increase priority a bit
  1145. ret.push_back(sptr(Goals::VisitTile(dest).sethero(h).setobjid(obj->ID.num).setisAbstract(true))); //TODO: change to getObj eventually and and move appropiate logic there
  1146. else
  1147. ret.push_back(sptr(Goals::VisitTile(dest).sethero(h).setisAbstract(true)));
  1148. }
  1149. }
  1150. }
  1151. else //we need to get army in order to conquer that place
  1152. ret.push_back(sptr(Goals::GatherArmy(evaluateDanger(dest, h) * SAFE_ATTACK_CONSTANT).sethero(h).setisAbstract(true)));
  1153. }
  1154. }
  1155. }
  1156. }
  1157. if(!objs.empty() && ai->canRecruitAnyHero()) //probably no point to recruit hero if we see no objects to capture
  1158. ret.push_back(sptr(Goals::RecruitHero()));
  1159. if(ret.empty())
  1160. ret.push_back(sptr(Goals::Explore())); //we need to find an enemy
  1161. return ret;
  1162. }
  1163. TSubgoal Build::whatToDoToAchieve()
  1164. {
  1165. return iAmElementar();
  1166. }
  1167. bool Goals::Build::fulfillsMe(TSubgoal goal)
  1168. {
  1169. if (goal->goalType == Goals::BUILD || goal->goalType == Goals::BUILD_STRUCTURE)
  1170. return (!town || town == goal->town); //building anything will do, in this town if set
  1171. else
  1172. return false;
  1173. }
  1174. TSubgoal Invalid::whatToDoToAchieve()
  1175. {
  1176. return iAmElementar();
  1177. }
  1178. std::string GatherArmy::completeMessage() const
  1179. {
  1180. return "Hero " + hero.get()->name + " gathered army of value " + boost::lexical_cast<std::string>(value);
  1181. }
  1182. TSubgoal GatherArmy::whatToDoToAchieve()
  1183. {
  1184. //TODO: find hero if none set
  1185. assert(hero.h);
  1186. return fh->chooseSolution(getAllPossibleSubgoals()); //find dwelling. use current hero to prevent him from doing nothing.
  1187. }
  1188. static const BuildingID unitsSource[] = { BuildingID::DWELL_LVL_1, BuildingID::DWELL_LVL_2, BuildingID::DWELL_LVL_3,
  1189. BuildingID::DWELL_LVL_4, BuildingID::DWELL_LVL_5, BuildingID::DWELL_LVL_6, BuildingID::DWELL_LVL_7};
  1190. TGoalVec GatherArmy::getAllPossibleSubgoals()
  1191. {
  1192. //get all possible towns, heroes and dwellings we may use
  1193. TGoalVec ret;
  1194. //TODO: include evaluation of monsters gather in calculation
  1195. for(auto t : cb->getTownsInfo())
  1196. {
  1197. auto pos = t->visitablePos();
  1198. if(ai->isAccessibleForHero(pos, hero))
  1199. {
  1200. //grab army from town
  1201. if(!t->visitingHero && howManyReinforcementsCanGet(hero, t))
  1202. {
  1203. if(!vstd::contains(ai->townVisitsThisWeek[hero], t))
  1204. ret.push_back(sptr(Goals::VisitTile(pos).sethero(hero)));
  1205. }
  1206. //buy army in town
  1207. if (!t->visitingHero || t->visitingHero != hero.get(true))
  1208. {
  1209. ui32 val = std::min<ui32>(value, howManyReinforcementsCanBuy(hero, t));
  1210. if (val)
  1211. {
  1212. auto goal = sptr(Goals::BuyArmy(t, val).sethero(hero));
  1213. if (!ah->containsObjective(goal)) //avoid loops caused by reserving same objective twice
  1214. ret.push_back(goal);
  1215. }
  1216. }
  1217. //build dwelling
  1218. auto bid = ai->canBuildAnyStructure(t, std::vector<BuildingID>(unitsSource, unitsSource + ARRAY_COUNT(unitsSource)), 8 - cb->getDate(Date::DAY_OF_WEEK));
  1219. if (bid != BuildingID::NONE)
  1220. {
  1221. auto goal = sptr(BuildThis(bid, t).setpriority(priority));
  1222. if (!ah->containsObjective(goal)) //avoid loops caused by reserving same objective twice
  1223. ret.push_back(goal);
  1224. }
  1225. }
  1226. }
  1227. auto otherHeroes = cb->getHeroesInfo();
  1228. auto heroDummy = hero;
  1229. vstd::erase_if(otherHeroes, [heroDummy](const CGHeroInstance * h)
  1230. {
  1231. if(h == heroDummy.h)
  1232. return true;
  1233. else if(!ai->isAccessibleForHero(heroDummy->visitablePos(), h, true))
  1234. return true;
  1235. else if(!ai->canGetArmy(heroDummy.h, h))
  1236. return true;
  1237. else if(ai->getGoal(h)->goalType == Goals::GATHER_ARMY)
  1238. return true;
  1239. else
  1240. return false;
  1241. });
  1242. for(auto h : otherHeroes)
  1243. {
  1244. // Go to the other hero if we are faster
  1245. ret.push_back(sptr(Goals::VisitHero(h->id.getNum()).setisAbstract(true).sethero(hero)));
  1246. // Let the other hero come to us
  1247. ret.push_back(sptr(Goals::VisitHero(hero->id.getNum()).setisAbstract(true).sethero(h)));
  1248. }
  1249. std::vector<const CGObjectInstance *> objs;
  1250. for(auto obj : ai->visitableObjs)
  1251. {
  1252. if(obj->ID == Obj::CREATURE_GENERATOR1)
  1253. {
  1254. auto relationToOwner = cb->getPlayerRelations(obj->getOwner(), ai->playerID);
  1255. //Use flagged dwellings only when there are available creatures that we can afford
  1256. if(relationToOwner == PlayerRelations::SAME_PLAYER)
  1257. {
  1258. auto dwelling = dynamic_cast<const CGDwelling *>(obj);
  1259. for(auto & creLevel : dwelling->creatures)
  1260. {
  1261. if(creLevel.first)
  1262. {
  1263. for(auto & creatureID : creLevel.second)
  1264. {
  1265. auto creature = VLC->creh->creatures[creatureID];
  1266. if(ah->freeResources().canAfford(creature->cost))
  1267. objs.push_back(obj);
  1268. }
  1269. }
  1270. }
  1271. }
  1272. }
  1273. }
  1274. for(auto h : cb->getHeroesInfo())
  1275. {
  1276. auto sm = ai->getCachedSectorMap(h);
  1277. for(auto obj : objs)
  1278. {
  1279. //find safe dwelling
  1280. auto pos = obj->visitablePos();
  1281. if(ai->isGoodForVisit(obj, h, *sm))
  1282. ret.push_back(sptr(Goals::VisitTile(pos).sethero(h)));
  1283. }
  1284. }
  1285. if(ai->canRecruitAnyHero() && ah->freeGold() > GameConstants::HERO_GOLD_COST) //this is not stupid in early phase of game
  1286. {
  1287. if(auto t = ai->findTownWithTavern())
  1288. {
  1289. for(auto h : cb->getAvailableHeroes(t)) //we assume that all towns have same set of heroes
  1290. {
  1291. if(h && h->getTotalStrength() > 500) //do not buy heroes with single creatures for GatherArmy
  1292. {
  1293. ret.push_back(sptr(Goals::RecruitHero()));
  1294. break;
  1295. }
  1296. }
  1297. }
  1298. }
  1299. if(ret.empty())
  1300. {
  1301. if(hero == ai->primaryHero() || value >= 1.1f) // FIXME: check PR388
  1302. ret.push_back(sptr(Goals::Explore()));
  1303. else //workaround to break loop - seemingly there are no ways to explore left
  1304. throw goalFulfilledException(sptr(Goals::GatherArmy(0).sethero(hero)));
  1305. }
  1306. return ret;
  1307. }
  1308. //TSubgoal AbstractGoal::whatToDoToAchieve()
  1309. //{
  1310. // logAi->debug("Decomposing goal of type %s",name());
  1311. // return sptr (Goals::Explore());
  1312. //}
  1313. TSubgoal AbstractGoal::goVisitOrLookFor(const CGObjectInstance * obj)
  1314. {
  1315. if(obj)
  1316. return sptr(Goals::GetObj(obj->id.getNum()));
  1317. else
  1318. return sptr(Goals::Explore());
  1319. }
  1320. TSubgoal AbstractGoal::lookForArtSmart(int aid)
  1321. {
  1322. return sptr(Goals::Invalid());
  1323. }
  1324. bool AbstractGoal::invalid() const
  1325. {
  1326. return goalType == INVALID;
  1327. }
  1328. void AbstractGoal::accept(VCAI * ai)
  1329. {
  1330. ai->tryRealize(*this);
  1331. }
  1332. template<typename T>
  1333. void CGoal<T>::accept(VCAI * ai)
  1334. {
  1335. ai->tryRealize(static_cast<T &>(*this)); //casting enforces template instantiation
  1336. }
  1337. float AbstractGoal::accept(FuzzyHelper * f)
  1338. {
  1339. return f->evaluate(*this);
  1340. }
  1341. template<typename T>
  1342. float CGoal<T>::accept(FuzzyHelper * f)
  1343. {
  1344. return f->evaluate(static_cast<T &>(*this)); //casting enforces template instantiation
  1345. }