Goals.cpp 43 KB

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