Goals.cpp 30 KB

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