2
0

Goals.cpp 33 KB

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