Goals.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  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 "../../lib/mapping/CMap.h" //for victory conditions
  15. #include "../../lib/CPathfinder.h"
  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 Goals;
  20. TSubgoal Goals::sptr(const AbstractGoal & tmp)
  21. {
  22. std::shared_ptr<AbstractGoal> ptr;
  23. ptr.reset(tmp.clone());
  24. return ptr;
  25. }
  26. std::string Goals::AbstractGoal::name() const //TODO: virtualize
  27. {
  28. std::string desc;
  29. switch (goalType)
  30. {
  31. case INVALID:
  32. return "INVALID";
  33. case WIN:
  34. return "WIN";
  35. case DO_NOT_LOSE:
  36. return "DO NOT LOOSE";
  37. case CONQUER:
  38. return "CONQUER";
  39. case BUILD:
  40. return "BUILD";
  41. case EXPLORE:
  42. desc = "EXPLORE";
  43. break;
  44. case GATHER_ARMY:
  45. desc = "GATHER ARMY";
  46. break;
  47. case BOOST_HERO:
  48. desc = "BOOST_HERO (unsupported)";
  49. break;
  50. case RECRUIT_HERO:
  51. return "RECRUIT HERO";
  52. case BUILD_STRUCTURE:
  53. return "BUILD STRUCTURE";
  54. case COLLECT_RES:
  55. desc = "COLLECT RESOURCE";
  56. break;
  57. case GATHER_TROOPS:
  58. desc = "GATHER TROOPS";
  59. break;
  60. case GET_OBJ:
  61. {
  62. auto obj = cb->getObjInstance(ObjectInstanceID(objid));
  63. if(obj)
  64. desc = "GET OBJ " + obj->getObjectName();
  65. }
  66. break;
  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.toString();
  84. break;
  85. case CLEAR_WAY_TO:
  86. desc = "CLEAR WAY TO " + tile.toString();
  87. break;
  88. case DIG_AT_TILE:
  89. desc = "DIG AT TILE " + tile.toString();
  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->debug("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. case EventCondition::HAVE_0:
  306. case EventCondition::HAVE_BUILDING_0:
  307. case EventCondition::DESTROY_0:
  308. //TODO: support new condition format
  309. return sptr (Goals::Conquer());
  310. default:
  311. assert(0);
  312. }
  313. }
  314. return sptr (Goals::Invalid());
  315. }
  316. TSubgoal FindObj::whatToDoToAchieve()
  317. {
  318. const CGObjectInstance * o = nullptr;
  319. if (resID > -1) //specified
  320. {
  321. for(const CGObjectInstance *obj : ai->visitableObjs)
  322. {
  323. if(obj->ID == objid && obj->subID == resID)
  324. {
  325. o = obj;
  326. break; //TODO: consider multiple objects and choose best
  327. }
  328. }
  329. }
  330. else
  331. {
  332. for(const CGObjectInstance *obj : ai->visitableObjs)
  333. {
  334. if(obj->ID == objid)
  335. {
  336. o = obj;
  337. break; //TODO: consider multiple objects and choose best
  338. }
  339. }
  340. }
  341. if (o && ai->isAccessible(o->pos)) //we don't use isAccessibleForHero as we don't know which hero it is
  342. return sptr (Goals::GetObj(o->id.getNum()));
  343. else
  344. return sptr (Goals::Explore());
  345. }
  346. std::string GetObj::completeMessage() const
  347. {
  348. return "hero " + hero.get()->name + " captured Object ID = " + boost::lexical_cast<std::string>(objid);
  349. }
  350. TSubgoal GetObj::whatToDoToAchieve()
  351. {
  352. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(objid));
  353. if(!obj)
  354. return sptr (Goals::Explore());
  355. if (obj->tempOwner == ai->playerID) //we can't capture our own object -> move to Win codition
  356. throw cannotFulfillGoalException("Cannot capture my own object " + obj->getObjectName());
  357. int3 pos = obj->visitablePos();
  358. if (hero)
  359. {
  360. if (ai->isAccessibleForHero(pos, hero))
  361. return sptr (Goals::VisitTile(pos).sethero(hero));
  362. }
  363. else
  364. {
  365. for (auto h : cb->getHeroesInfo())
  366. {
  367. if (ai->isAccessibleForHero(pos, h))
  368. return sptr(Goals::VisitTile(pos).sethero(h)); //we must visit object with same hero, if any
  369. }
  370. }
  371. return sptr (Goals::ClearWayTo(pos).sethero(hero));
  372. }
  373. bool GetObj::fulfillsMe (TSubgoal goal)
  374. {
  375. if (goal->goalType == Goals::VISIT_TILE)
  376. {
  377. auto obj = cb->getObj(ObjectInstanceID(objid));
  378. if (obj && obj->visitablePos() == goal->tile) //object could be removed
  379. return true;
  380. }
  381. return false;
  382. }
  383. std::string VisitHero::completeMessage() const
  384. {
  385. return "hero " + hero.get()->name + " visited hero " + boost::lexical_cast<std::string>(objid);
  386. }
  387. TSubgoal VisitHero::whatToDoToAchieve()
  388. {
  389. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(objid));
  390. if(!obj)
  391. return sptr (Goals::Explore());
  392. int3 pos = obj->visitablePos();
  393. if (hero && ai->isAccessibleForHero(pos, hero, true) && isSafeToVisit(hero, pos)) //enemy heroes can get reinforcements
  394. {
  395. if (hero->pos == pos)
  396. logAi->error("Hero %s tries to visit himself.", hero.name);
  397. else
  398. {
  399. //can't use VISIT_TILE here as tile appears blocked by target hero
  400. //FIXME: elementar goal should not be abstract
  401. return sptr (Goals::VisitHero(objid).sethero(hero).settile(pos).setisElementar(true));
  402. }
  403. }
  404. return sptr (Goals::Invalid());
  405. }
  406. bool VisitHero::fulfillsMe (TSubgoal goal)
  407. {
  408. if (goal->goalType != Goals::VISIT_TILE)
  409. {
  410. return false;
  411. }
  412. auto obj = cb->getObj(ObjectInstanceID(objid));
  413. if (!obj)
  414. {
  415. logAi->error("Hero %s: VisitHero::fulfillsMe at %s: object %d not found", hero.name, goal->tile.toString(), objid);
  416. return false;
  417. }
  418. return obj->visitablePos() == goal->tile;
  419. }
  420. TSubgoal GetArtOfType::whatToDoToAchieve()
  421. {
  422. TSubgoal alternativeWay = CGoal::lookForArtSmart(aid); //TODO: use
  423. if(alternativeWay->invalid())
  424. return sptr (Goals::FindObj(Obj::ARTIFACT, aid));
  425. return sptr (Goals::Invalid());
  426. }
  427. TSubgoal ClearWayTo::whatToDoToAchieve()
  428. {
  429. assert(cb->isInTheMap(tile)); //set tile
  430. if(!cb->isVisible(tile))
  431. {
  432. logAi->error("Clear way should be used with visible tiles!");
  433. return sptr (Goals::Explore());
  434. }
  435. return (fh->chooseSolution(getAllPossibleSubgoals()));
  436. }
  437. TGoalVec ClearWayTo::getAllPossibleSubgoals()
  438. {
  439. TGoalVec ret;
  440. std::vector<const CGHeroInstance *> heroes;
  441. if (hero)
  442. heroes.push_back(hero.h);
  443. else
  444. {
  445. heroes = cb->getHeroesInfo();
  446. }
  447. for (auto h : heroes)
  448. {
  449. //TODO: handle clearing way to allied heroes that are blocked
  450. //if ((hero && hero->visitablePos() == tile && hero == *h) || //we can't free the way ourselves
  451. // h->visitablePos() == tile) //we are already on that tile! what does it mean?
  452. // continue;
  453. //if our hero is trapped, make sure we request clearing the way from OUR perspective
  454. auto sm = ai->getCachedSectorMap(h);
  455. int3 tileToHit = sm->firstTileToGet(h, tile);
  456. if (!tileToHit.valid())
  457. continue;
  458. if (isBlockedBorderGate(tileToHit))
  459. { //FIXME: this way we'll not visit gate and activate quest :?
  460. ret.push_back (sptr (Goals::FindObj (Obj::KEYMASTER, cb->getTile(tileToHit)->visitableObjects.back()->subID)));
  461. }
  462. auto topObj = cb->getTopObj(tileToHit);
  463. if (topObj)
  464. {
  465. if (vstd::contains(ai->reservedObjs, topObj) && !vstd::contains(ai->reservedHeroesMap[h], topObj))
  466. {
  467. throw goalFulfilledException (sptr(Goals::ClearWayTo(tile, h)));
  468. continue; //do not capure object reserved by other hero
  469. }
  470. if (topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES)
  471. if (topObj != hero.get(true)) //the hero we want to free
  472. logAi->error("%s stands in the way of %s", topObj->getObjectName(), h->getObjectName());
  473. if (topObj->ID == Obj::QUEST_GUARD || topObj->ID == Obj::BORDERGUARD)
  474. {
  475. if (shouldVisit(h, topObj))
  476. {
  477. //do NOT use VISIT_TILE, as tile with quets guard can't be visited
  478. ret.push_back (sptr (Goals::GetObj(topObj->id.getNum()).sethero(h)));
  479. continue; //do not try to visit tile or gather army
  480. }
  481. else
  482. {
  483. //TODO: we should be able to return apriopriate quest here (VCAI::striveToQuest)
  484. logAi->debug("Quest guard blocks the way to %s", tile.toString());
  485. continue; //do not access quets guard if we can't complete the quest
  486. }
  487. }
  488. }
  489. if (isSafeToVisit(h, tileToHit)) //this makes sense only if tile is guarded, but there i no quest object
  490. {
  491. ret.push_back (sptr (Goals::VisitTile(tileToHit).sethero(h)));
  492. }
  493. else
  494. {
  495. ret.push_back (sptr (Goals::GatherArmy(evaluateDanger(tileToHit, h)*SAFE_ATTACK_CONSTANT).
  496. sethero(h).setisAbstract(true)));
  497. }
  498. }
  499. if (ai->canRecruitAnyHero())
  500. ret.push_back (sptr (Goals::RecruitHero()));
  501. if (ret.empty())
  502. {
  503. logAi->warn("There is no known way to clear the way to tile %s", tile.toString());
  504. throw goalFulfilledException (sptr(Goals::ClearWayTo(tile))); //make sure asigned hero gets unlocked
  505. }
  506. return ret;
  507. }
  508. std::string Explore::completeMessage() const
  509. {
  510. return "Hero " + hero.get()->name + " completed exploration";
  511. }
  512. TSubgoal Explore::whatToDoToAchieve()
  513. {
  514. auto ret = fh->chooseSolution(getAllPossibleSubgoals());
  515. if (hero) //use best step for this hero
  516. return ret;
  517. else
  518. {
  519. if (ret->hero.get(true))
  520. return sptr (sethero(ret->hero.h).setisAbstract(true)); //choose this hero and then continue with him
  521. else
  522. return ret; //other solutions, like buying hero from tavern
  523. }
  524. }
  525. TGoalVec Explore::getAllPossibleSubgoals()
  526. {
  527. TGoalVec ret;
  528. std::vector<const CGHeroInstance *> heroes;
  529. if (hero)
  530. heroes.push_back(hero.h);
  531. else
  532. {
  533. //heroes = ai->getUnblockedHeroes();
  534. heroes = cb->getHeroesInfo();
  535. vstd::erase_if(heroes, [](const HeroPtr h)
  536. {
  537. if (ai->getGoal(h)->goalType == Goals::EXPLORE) //do not reassign hero who is already explorer
  538. return true;
  539. if (!ai->isAbleToExplore(h))
  540. return true;
  541. return !h->movement; //saves time, immobile heroes are useless anyway
  542. });
  543. }
  544. //try to use buildings that uncover map
  545. std::vector<const CGObjectInstance *> objs;
  546. for (auto obj : ai->visitableObjs)
  547. {
  548. if (!vstd::contains(ai->alreadyVisited, obj))
  549. {
  550. switch (obj->ID.num)
  551. {
  552. case Obj::REDWOOD_OBSERVATORY:
  553. case Obj::PILLAR_OF_FIRE:
  554. case Obj::CARTOGRAPHER:
  555. objs.push_back (obj);
  556. break;
  557. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  558. case Obj::MONOLITH_TWO_WAY:
  559. case Obj::SUBTERRANEAN_GATE:
  560. auto tObj = dynamic_cast<const CGTeleport *>(obj);
  561. assert(ai->knownTeleportChannels.find(tObj->channel) != ai->knownTeleportChannels.end());
  562. if(TeleportChannel::IMPASSABLE != ai->knownTeleportChannels[tObj->channel]->passability)
  563. objs.push_back (obj);
  564. break;
  565. }
  566. }
  567. else
  568. {
  569. switch (obj->ID.num)
  570. {
  571. case Obj::MONOLITH_TWO_WAY:
  572. case Obj::SUBTERRANEAN_GATE:
  573. auto tObj = dynamic_cast<const CGTeleport *>(obj);
  574. if(TeleportChannel::IMPASSABLE == ai->knownTeleportChannels[tObj->channel]->passability)
  575. break;
  576. for(auto exit : ai->knownTeleportChannels[tObj->channel]->exits)
  577. {
  578. if(!cb->getObj(exit))
  579. { // Always attempt to visit two-way teleports if one of channel exits is not visible
  580. objs.push_back(obj);
  581. break;
  582. }
  583. }
  584. break;
  585. }
  586. }
  587. }
  588. for (auto h : heroes)
  589. {
  590. auto sm = ai->getCachedSectorMap(h);
  591. for (auto obj : objs) //double loop, performance risk?
  592. {
  593. auto t = sm->firstTileToGet(h, obj->visitablePos()); //we assume that no more than one tile on the way is guarded
  594. if (ai->isTileNotReserved(h, t))
  595. ret.push_back (sptr(Goals::ClearWayTo(obj->visitablePos(), h).setisAbstract(true)));
  596. }
  597. int3 t = whereToExplore(h);
  598. if (t.valid())
  599. {
  600. ret.push_back (sptr (Goals::VisitTile(t).sethero(h)));
  601. }
  602. else
  603. {
  604. ai->markHeroUnableToExplore (h); //there is no freely accessible tile, do not poll this hero anymore
  605. //possible issues when gathering army to break
  606. if (hero.h == h || (!hero && h == ai->primaryHero().h)) //check this only ONCE, high cost
  607. {
  608. t = ai->explorationDesperate(h);
  609. if (t.valid()) //don't waste time if we are completely blocked
  610. ret.push_back (sptr(Goals::ClearWayTo(t, h).setisAbstract(true)));
  611. }
  612. }
  613. }
  614. //we either don't have hero yet or none of heroes can explore
  615. if ((!hero || ret.empty()) && ai->canRecruitAnyHero())
  616. ret.push_back (sptr(Goals::RecruitHero()));
  617. if (ret.empty())
  618. {
  619. throw goalFulfilledException (sptr(Goals::Explore().sethero(hero)));
  620. }
  621. //throw cannotFulfillGoalException("Cannot explore - no possible ways found!");
  622. return ret;
  623. }
  624. bool Explore::fulfillsMe (TSubgoal goal)
  625. {
  626. if (goal->goalType == Goals::EXPLORE)
  627. {
  628. if (goal->hero)
  629. return hero == goal->hero;
  630. else
  631. return true; //cancel ALL exploration
  632. }
  633. return false;
  634. }
  635. TSubgoal RecruitHero::whatToDoToAchieve()
  636. {
  637. const CGTownInstance *t = ai->findTownWithTavern();
  638. if(!t)
  639. return sptr (Goals::BuildThis(BuildingID::TAVERN));
  640. if(cb->getResourceAmount(Res::GOLD) < GameConstants::HERO_GOLD_COST)
  641. return sptr (Goals::CollectRes(Res::GOLD, GameConstants::HERO_GOLD_COST));
  642. return iAmElementar();
  643. }
  644. std::string VisitTile::completeMessage() const
  645. {
  646. return "Hero " + hero.get()->name + " visited tile " + tile.toString();
  647. }
  648. TSubgoal VisitTile::whatToDoToAchieve()
  649. {
  650. auto ret = fh->chooseSolution(getAllPossibleSubgoals());
  651. if(ret->hero)
  652. {
  653. if(isSafeToVisit(ret->hero, tile) && ai->isAccessibleForHero(tile, ret->hero))
  654. {
  655. if(cb->getTile(tile)->topVisitableId().num == Obj::TOWN) //if target is town, fuzzy system will use additional "estimatedReward" variable to increase priority a bit
  656. ret->objid = Obj::TOWN; //TODO: move to getObj eventually and add appropiate logic there
  657. ret->setisElementar(true);
  658. return ret;
  659. }
  660. else
  661. {
  662. return sptr (Goals::GatherArmy(evaluateDanger(tile, *ret->hero) * SAFE_ATTACK_CONSTANT)
  663. .sethero(ret->hero).setisAbstract(true));
  664. }
  665. }
  666. return ret;
  667. }
  668. TGoalVec VisitTile::getAllPossibleSubgoals()
  669. {
  670. assert(cb->isInTheMap(tile));
  671. TGoalVec ret;
  672. if (!cb->isVisible(tile))
  673. ret.push_back (sptr(Goals::Explore())); //what sense does it make?
  674. else
  675. {
  676. std::vector<const CGHeroInstance *> heroes;
  677. if (hero)
  678. heroes.push_back(hero.h); //use assigned hero if any
  679. else
  680. heroes = cb->getHeroesInfo(); //use most convenient hero
  681. for (auto h : heroes)
  682. {
  683. if (ai->isAccessibleForHero(tile, h))
  684. ret.push_back (sptr(Goals::VisitTile(tile).sethero(h)));
  685. }
  686. if (ai->canRecruitAnyHero())
  687. ret.push_back (sptr(Goals::RecruitHero()));
  688. }
  689. if(ret.empty())
  690. {
  691. auto obj = vstd::frontOrNull(cb->getVisitableObjs(tile));
  692. if(obj && obj->ID == Obj::HERO && obj->tempOwner == ai->playerID) //our own hero stands on that tile
  693. {
  694. 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
  695. ret.push_back(sptr(Goals::VisitTile(tile).sethero(dynamic_cast<const CGHeroInstance *>(obj)).setisElementar(true)));
  696. else
  697. throw cannotFulfillGoalException("Tile is already occupied by another hero "); //FIXME: we should give up this tile earlier
  698. }
  699. else
  700. ret.push_back (sptr(Goals::ClearWayTo(tile)));
  701. }
  702. //important - at least one sub-goal must handle case which is impossible to fulfill (unreachable tile)
  703. return ret;
  704. }
  705. TSubgoal DigAtTile::whatToDoToAchieve()
  706. {
  707. const CGObjectInstance *firstObj = vstd::frontOrNull(cb->getVisitableObjs(tile));
  708. if(firstObj && firstObj->ID == Obj::HERO && firstObj->tempOwner == ai->playerID) //we have hero at dest
  709. {
  710. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(firstObj);
  711. sethero(h).setisElementar(true);
  712. return sptr (*this);
  713. }
  714. return sptr (Goals::VisitTile(tile));
  715. }
  716. TSubgoal BuildThis::whatToDoToAchieve()
  717. {
  718. //TODO check res
  719. //look for town
  720. //prerequisites?
  721. return iAmElementar();
  722. }
  723. TSubgoal CollectRes::whatToDoToAchieve()
  724. {
  725. std::vector<const IMarket*> markets;
  726. std::vector<const CGObjectInstance*> visObjs;
  727. ai->retrieveVisitableObjs(visObjs, true);
  728. for(const CGObjectInstance *obj : visObjs)
  729. {
  730. if(const IMarket *m = IMarket::castFrom(obj, false))
  731. {
  732. if(obj->ID == Obj::TOWN && obj->tempOwner == ai->playerID && m->allowsTrade(EMarketMode::RESOURCE_RESOURCE))
  733. markets.push_back(m);
  734. else if(obj->ID == Obj::TRADING_POST) //TODO a moze po prostu test na pozwalanie handlu?
  735. markets.push_back(m);
  736. }
  737. }
  738. boost::sort(markets, [](const IMarket *m1, const IMarket *m2) -> bool
  739. {
  740. return m1->getMarketEfficiency() < m2->getMarketEfficiency();
  741. });
  742. markets.erase(boost::remove_if(markets, [](const IMarket *market) -> bool
  743. {
  744. return !(market->o->ID == Obj::TOWN && market->o->tempOwner == ai->playerID)
  745. && !ai->isAccessible(market->o->visitablePos());
  746. }),markets.end());
  747. if(!markets.size())
  748. {
  749. for(const CGTownInstance *t : cb->getTownsInfo())
  750. {
  751. if(cb->canBuildStructure(t, BuildingID::MARKETPLACE) == EBuildingState::ALLOWED)
  752. return sptr (Goals::BuildThis(BuildingID::MARKETPLACE, t));
  753. }
  754. }
  755. else
  756. {
  757. const IMarket *m = markets.back();
  758. //attempt trade at back (best prices)
  759. int howManyCanWeBuy = 0;
  760. for(Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
  761. {
  762. if(i == resID) continue;
  763. int toGive = -1, toReceive = -1;
  764. m->getOffer(i, resID, toGive, toReceive, EMarketMode::RESOURCE_RESOURCE);
  765. assert(toGive > 0 && toReceive > 0);
  766. howManyCanWeBuy += toReceive * (cb->getResourceAmount(i) / toGive);
  767. }
  768. if(howManyCanWeBuy + cb->getResourceAmount(static_cast<Res::ERes>(resID)) >= value)
  769. {
  770. auto backObj = cb->getTopObj(m->o->visitablePos()); //it'll be a hero if we have one there; otherwise marketplace
  771. assert(backObj);
  772. if (backObj->tempOwner != ai->playerID)
  773. {
  774. return sptr (Goals::GetObj(m->o->id.getNum()));
  775. }
  776. else
  777. {
  778. return sptr (Goals::GetObj(m->o->id.getNum()).setisElementar(true));
  779. }
  780. }
  781. }
  782. return sptr (setisElementar(true)); //all the conditions for trade are met
  783. }
  784. TSubgoal GatherTroops::whatToDoToAchieve()
  785. {
  786. std::vector<const CGDwelling *> dwellings;
  787. for(const CGTownInstance *t : cb->getTownsInfo())
  788. {
  789. auto creature = VLC->creh->creatures[objid];
  790. if (t->subID == creature->faction) //TODO: how to force AI to build unupgraded creatures? :O
  791. {
  792. auto creatures = vstd::tryAt(t->town->creatures, creature->level - 1);
  793. if(!creatures)
  794. continue;
  795. int upgradeNumber = vstd::find_pos(*creatures, creature->idNumber);
  796. if(upgradeNumber < 0)
  797. continue;
  798. BuildingID bid(BuildingID::DWELL_FIRST + creature->level - 1 + upgradeNumber * GameConstants::CREATURES_PER_TOWN);
  799. if (t->hasBuilt(bid)) //this assumes only creatures with dwellings are assigned to faction
  800. {
  801. dwellings.push_back(t);
  802. }
  803. else
  804. {
  805. return sptr (Goals::BuildThis(bid, t));
  806. }
  807. }
  808. }
  809. for (auto obj : ai->visitableObjs)
  810. {
  811. if (obj->ID != Obj::CREATURE_GENERATOR1) //TODO: what with other creature generators?
  812. continue;
  813. auto d = dynamic_cast<const CGDwelling *>(obj);
  814. for (auto creature : d->creatures)
  815. {
  816. if (creature.first) //there are more than 0 creatures avaliabe
  817. {
  818. for (auto type : creature.second)
  819. {
  820. if (type == objid && ai->freeResources().canAfford(VLC->creh->creatures[type]->cost))
  821. dwellings.push_back(d);
  822. }
  823. }
  824. }
  825. }
  826. if (dwellings.size())
  827. {
  828. typedef std::map<const CGHeroInstance *, const CGDwelling *> TDwellMap;
  829. // sorted helper
  830. auto comparator = [](const TDwellMap::value_type & a, const TDwellMap::value_type & b) -> bool
  831. {
  832. const CGPathNode *ln = ai->myCb->getPathsInfo(a.first)->getPathInfo(a.second->visitablePos()),
  833. *rn = ai->myCb->getPathsInfo(b.first)->getPathInfo(b.second->visitablePos());
  834. if(ln->turns != rn->turns)
  835. return ln->turns < rn->turns;
  836. return (ln->moveRemains > rn->moveRemains);
  837. };
  838. // for all owned heroes generate map <hero -> nearest dwelling>
  839. TDwellMap nearestDwellings;
  840. for (const CGHeroInstance * hero : cb->getHeroesInfo(true))
  841. {
  842. nearestDwellings[hero] = *boost::range::min_element(dwellings, CDistanceSorter(hero));
  843. }
  844. if (nearestDwellings.size())
  845. {
  846. // find hero who is nearest to a dwelling
  847. const CGDwelling * nearest = boost::range::min_element(nearestDwellings, comparator)->second;
  848. if (!nearest)
  849. throw cannotFulfillGoalException("Cannot find nearest dwelling!");
  850. return sptr(Goals::GetObj(nearest->id.getNum()));
  851. }
  852. else
  853. return sptr(Goals::Explore());
  854. }
  855. else
  856. return sptr (Goals::Explore());
  857. //TODO: exchange troops between heroes
  858. }
  859. TSubgoal Conquer::whatToDoToAchieve()
  860. {
  861. return fh->chooseSolution (getAllPossibleSubgoals());
  862. }
  863. TGoalVec Conquer::getAllPossibleSubgoals()
  864. {
  865. TGoalVec ret;
  866. auto conquerable = [](const CGObjectInstance * obj) -> bool
  867. {
  868. if (cb->getPlayerRelations(ai->playerID, obj->tempOwner) == PlayerRelations::ENEMIES)
  869. {
  870. switch (obj->ID.num)
  871. {
  872. case Obj::TOWN:
  873. case Obj::HERO:
  874. case Obj::CREATURE_GENERATOR1:
  875. case Obj::MINE: //TODO: check ai->knownSubterraneanGates
  876. return true;
  877. }
  878. }
  879. return false;
  880. };
  881. std::vector<const CGObjectInstance *> objs;
  882. for(auto obj : ai->visitableObjs)
  883. {
  884. if(conquerable(obj))
  885. objs.push_back (obj);
  886. }
  887. for(auto h : cb->getHeroesInfo())
  888. {
  889. auto sm = ai->getCachedSectorMap(h);
  890. std::vector<const CGObjectInstance *> ourObjs(objs); //copy common objects
  891. for(auto obj : ai->reservedHeroesMap[h]) //add objects reserved by this hero
  892. {
  893. if(conquerable(obj))
  894. ourObjs.push_back(obj);
  895. }
  896. for(auto obj : ourObjs)
  897. {
  898. int3 dest = obj->visitablePos();
  899. auto t = sm->firstTileToGet(h, dest); //we assume that no more than one tile on the way is guarded
  900. if(t.valid()) //we know any path at all
  901. {
  902. if(ai->isTileNotReserved(h, t)) //no other hero wants to conquer that tile
  903. {
  904. if(isSafeToVisit(h, dest))
  905. {
  906. if(dest != t) //there is something blocking our way
  907. ret.push_back(sptr(Goals::ClearWayTo(dest, h).setisAbstract(true)));
  908. else
  909. {
  910. if(obj->ID.num == Obj::HERO) //enemy hero may move to other position
  911. {
  912. ret.push_back(sptr(Goals::VisitHero(obj->id.getNum()).sethero(h).setisAbstract(true)));
  913. }
  914. else //just visit that tile
  915. {
  916. if(obj->ID.num == Obj::TOWN)
  917. //if target is town, fuzzy system will use additional "estimatedReward" variable to increase priority a bit
  918. 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
  919. else
  920. ret.push_back(sptr(Goals::VisitTile(dest).sethero(h).setisAbstract(true)));
  921. }
  922. }
  923. }
  924. else //we need to get army in order to conquer that place
  925. ret.push_back(sptr(Goals::GatherArmy(evaluateDanger(dest, h) * SAFE_ATTACK_CONSTANT).sethero(h).setisAbstract(true)));
  926. }
  927. }
  928. }
  929. }
  930. if (!objs.empty() && ai->canRecruitAnyHero()) //probably no point to recruit hero if we see no objects to capture
  931. ret.push_back (sptr(Goals::RecruitHero()));
  932. if (ret.empty())
  933. ret.push_back (sptr(Goals::Explore())); //we need to find an enemy
  934. return ret;
  935. }
  936. TSubgoal Build::whatToDoToAchieve()
  937. {
  938. return iAmElementar();
  939. }
  940. TSubgoal Invalid::whatToDoToAchieve()
  941. {
  942. return iAmElementar();
  943. }
  944. std::string GatherArmy::completeMessage() const
  945. {
  946. return "Hero " + hero.get()->name + " gathered army of value " + boost::lexical_cast<std::string>(value);
  947. }
  948. TSubgoal GatherArmy::whatToDoToAchieve()
  949. {
  950. //TODO: find hero if none set
  951. assert(hero.h);
  952. return fh->chooseSolution (getAllPossibleSubgoals()); //find dwelling. use current hero to prevent him from doing nothing.
  953. }
  954. static const BuildingID unitsSource[] = { BuildingID::DWELL_LVL_1, BuildingID::DWELL_LVL_2, BuildingID::DWELL_LVL_3,
  955. BuildingID::DWELL_LVL_4, BuildingID::DWELL_LVL_5, BuildingID::DWELL_LVL_6, BuildingID::DWELL_LVL_7};
  956. TGoalVec GatherArmy::getAllPossibleSubgoals()
  957. {
  958. //get all possible towns, heroes and dwellings we may use
  959. TGoalVec ret;
  960. //TODO: include evaluation of monsters gather in calculation
  961. for (auto t : cb->getTownsInfo())
  962. {
  963. auto pos = t->visitablePos();
  964. if (ai->isAccessibleForHero(pos, hero))
  965. {
  966. if(!t->visitingHero && howManyReinforcementsCanGet(hero,t))
  967. {
  968. if (!vstd::contains (ai->townVisitsThisWeek[hero], t))
  969. ret.push_back (sptr (Goals::VisitTile(pos).sethero(hero)));
  970. }
  971. auto bid = ai->canBuildAnyStructure(t, std::vector<BuildingID>
  972. (unitsSource, unitsSource + ARRAY_COUNT(unitsSource)), 8 - cb->getDate(Date::DAY_OF_WEEK));
  973. if (bid != BuildingID::NONE)
  974. ret.push_back (sptr(BuildThis(bid, t)));
  975. }
  976. }
  977. auto otherHeroes = cb->getHeroesInfo();
  978. auto heroDummy = hero;
  979. vstd::erase_if(otherHeroes, [heroDummy](const CGHeroInstance * h)
  980. {
  981. return (h == heroDummy.h || !ai->isAccessibleForHero(heroDummy->visitablePos(), h, true)
  982. || !ai->canGetArmy(heroDummy.h, h) || ai->getGoal(h)->goalType == Goals::GATHER_ARMY);
  983. });
  984. for (auto h : otherHeroes)
  985. {
  986. ret.push_back (sptr (Goals::VisitHero(h->id.getNum()).setisAbstract(true).sethero(hero)));
  987. //go to the other hero if we are faster
  988. ret.push_back (sptr (Goals::VisitHero(hero->id.getNum()).setisAbstract(true).sethero(h)));
  989. //let the other hero come to us
  990. }
  991. std::vector <const CGObjectInstance *> objs;
  992. for (auto obj : ai->visitableObjs)
  993. {
  994. if(obj->ID == Obj::CREATURE_GENERATOR1)
  995. {
  996. auto relationToOwner = cb->getPlayerRelations(obj->getOwner(), ai->playerID);
  997. //Use flagged dwellings only when there are available creatures that we can afford
  998. if(relationToOwner == PlayerRelations::SAME_PLAYER)
  999. {
  1000. auto dwelling = dynamic_cast<const CGDwelling*>(obj);
  1001. for(auto & creLevel : dwelling->creatures)
  1002. {
  1003. if(creLevel.first)
  1004. {
  1005. for(auto & creatureID : creLevel.second)
  1006. {
  1007. auto creature = VLC->creh->creatures[creatureID];
  1008. if (ai->freeResources().canAfford(creature->cost))
  1009. objs.push_back(obj);
  1010. }
  1011. }
  1012. }
  1013. }
  1014. }
  1015. }
  1016. for(auto h : cb->getHeroesInfo())
  1017. {
  1018. auto sm = ai->getCachedSectorMap(h);
  1019. for (auto obj : objs)
  1020. { //find safe dwelling
  1021. auto pos = obj->visitablePos();
  1022. if (ai->isGoodForVisit(obj, h, *sm))
  1023. ret.push_back (sptr (Goals::VisitTile(pos).sethero(h)));
  1024. }
  1025. }
  1026. if(ai->canRecruitAnyHero() && ai->freeResources()[Res::GOLD] > GameConstants::HERO_GOLD_COST) //this is not stupid in early phase of game
  1027. {
  1028. if(auto t = ai->findTownWithTavern())
  1029. {
  1030. for (auto h : cb->getAvailableHeroes(t)) //we assume that all towns have same set of heroes
  1031. {
  1032. if(h && h->getTotalStrength() > 500) //do not buy heroes with single creatures for GatherArmy
  1033. {
  1034. ret.push_back(sptr(Goals::RecruitHero()));
  1035. break;
  1036. }
  1037. }
  1038. }
  1039. }
  1040. if (ret.empty())
  1041. {
  1042. if (hero == ai->primaryHero() || value >= 1.1f)
  1043. ret.push_back (sptr(Goals::Explore()));
  1044. else //workaround to break loop - seemingly there are no ways to explore left
  1045. throw goalFulfilledException (sptr(Goals::GatherArmy(0).sethero(hero)));
  1046. }
  1047. return ret;
  1048. }
  1049. //TSubgoal AbstractGoal::whatToDoToAchieve()
  1050. //{
  1051. // logAi->debug("Decomposing goal of type %s",name());
  1052. // return sptr (Goals::Explore());
  1053. //}
  1054. TSubgoal AbstractGoal::goVisitOrLookFor(const CGObjectInstance *obj)
  1055. {
  1056. if(obj)
  1057. return sptr (Goals::GetObj(obj->id.getNum()));
  1058. else
  1059. return sptr (Goals::Explore());
  1060. }
  1061. TSubgoal AbstractGoal::lookForArtSmart(int aid)
  1062. {
  1063. return sptr (Goals::Invalid());
  1064. }
  1065. bool AbstractGoal::invalid() const
  1066. {
  1067. return goalType == INVALID;
  1068. }
  1069. void AbstractGoal::accept (VCAI * ai)
  1070. {
  1071. ai->tryRealize(*this);
  1072. }
  1073. template<typename T>
  1074. void CGoal<T>::accept (VCAI * ai)
  1075. {
  1076. ai->tryRealize(static_cast<T&>(*this)); //casting enforces template instantiation
  1077. }
  1078. float AbstractGoal::accept (FuzzyHelper * f)
  1079. {
  1080. return f->evaluate(*this);
  1081. }
  1082. template<typename T>
  1083. float CGoal<T>::accept (FuzzyHelper * f)
  1084. {
  1085. return f->evaluate(static_cast<T&>(*this)); //casting enforces template instantiation
  1086. }