2
0

Goals.cpp 28 KB

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