Goals.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  1. #include "StdInc.h"
  2. #include "Goals.h"
  3. #include "VCAI.h"
  4. #include "Fuzzy.h"
  5. /*
  6. * Goals.cpp, part of VCMI engine
  7. *
  8. * Authors: listed in file AUTHORS in main folder
  9. *
  10. * License: GNU General Public License v2.0 or later
  11. * Full text of license available in license.txt file, in main folder
  12. *
  13. */
  14. extern boost::thread_specific_ptr<CCallback> cb;
  15. extern boost::thread_specific_ptr<VCAI> ai;
  16. extern FuzzyHelper * fh; //TODO: this logic should be moved inside VCAI
  17. using namespace vstd;
  18. using namespace Goals;
  19. TSubgoal Goals::sptr(const AbstractGoal & tmp)
  20. {
  21. shared_ptr<AbstractGoal> ptr;
  22. ptr.reset(tmp.clone());
  23. return ptr;
  24. }
  25. std::string Goals::AbstractGoal::name() const //TODO: virtualize
  26. {
  27. switch (goalType)
  28. {
  29. case INVALID:
  30. return "INVALID";
  31. case WIN:
  32. return "WIN";
  33. case DO_NOT_LOSE:
  34. return "DO NOT LOOSE";
  35. case CONQUER:
  36. return "CONQUER";
  37. case BUILD:
  38. return "BUILD";
  39. case EXPLORE:
  40. return "EXPLORE";
  41. case GATHER_ARMY:
  42. return "GATHER ARMY";
  43. case BOOST_HERO:
  44. return "BOOST_HERO (unsupported)";
  45. case RECRUIT_HERO:
  46. return "RECRUIT HERO";
  47. case BUILD_STRUCTURE:
  48. return "BUILD STRUCTURE";
  49. case COLLECT_RES:
  50. return "COLLECT RESOURCE";
  51. case GATHER_TROOPS:
  52. return "GATHER TROOPS";
  53. case GET_OBJ:
  54. return "GET OBJECT " + boost::lexical_cast<std::string>(objid);
  55. case FIND_OBJ:
  56. return "FIND OBJECT " + boost::lexical_cast<std::string>(objid);
  57. case VISIT_HERO:
  58. return "VISIT HERO " + boost::lexical_cast<std::string>(objid);
  59. case GET_ART_TYPE:
  60. return "GET ARTIFACT OF TYPE " + VLC->arth->artifacts[aid]->Name();
  61. case ISSUE_COMMAND:
  62. return "ISSUE COMMAND (unsupported)";
  63. case VISIT_TILE:
  64. return "VISIT TILE " + tile();
  65. case CLEAR_WAY_TO:
  66. return "CLEAR WAY TO " + tile();
  67. case DIG_AT_TILE:
  68. return "DIG AT TILE " + tile();
  69. default:
  70. return boost::lexical_cast<std::string>(goalType);
  71. }
  72. }
  73. //TODO: find out why the following are not generated automatically on MVS?
  74. namespace Goals
  75. {
  76. template <>
  77. void CGoal<Win>::accept (VCAI * ai)
  78. {
  79. ai->tryRealize(static_cast<Win&>(*this));
  80. }
  81. template <>
  82. void CGoal<Build>::accept (VCAI * ai)
  83. {
  84. ai->tryRealize(static_cast<Build&>(*this));
  85. }
  86. template <>
  87. float CGoal<Win>::accept (FuzzyHelper * f)
  88. {
  89. return f->evaluate(static_cast<Win&>(*this));
  90. }
  91. template <>
  92. float CGoal<Build>::accept (FuzzyHelper * f)
  93. {
  94. return f->evaluate(static_cast<Build&>(*this));
  95. }
  96. }
  97. //TSubgoal AbstractGoal::whatToDoToAchieve()
  98. //{
  99. // logAi->debugStream() << boost::format("Decomposing goal of type %s") % name();
  100. // return sptr (Goals::Explore());
  101. //}
  102. TSubgoal Win::whatToDoToAchieve()
  103. {
  104. const VictoryCondition &vc = cb->getMapHeader()->victoryCondition;
  105. EVictoryConditionType::EVictoryConditionType cond = vc.condition;
  106. if(!vc.appliesToAI)
  107. {
  108. //TODO deduce victory from human loss condition
  109. cond = EVictoryConditionType::WINSTANDARD;
  110. }
  111. switch(cond)
  112. {
  113. case EVictoryConditionType::ARTIFACT:
  114. return sptr (Goals::GetArtOfType(vc.objectId));
  115. case EVictoryConditionType::BEATHERO:
  116. return sptr (Goals::GetObj(vc.obj->id.getNum()));
  117. case EVictoryConditionType::BEATMONSTER:
  118. return sptr (Goals::GetObj(vc.obj->id.getNum()));
  119. case EVictoryConditionType::BUILDCITY:
  120. //TODO build castle/capitol
  121. break;
  122. case EVictoryConditionType::BUILDGRAIL:
  123. {
  124. if(auto h = ai->getHeroWithGrail())
  125. {
  126. //hero is in a town that can host Grail
  127. if(h->visitedTown && !vstd::contains(h->visitedTown->forbiddenBuildings, BuildingID::GRAIL))
  128. {
  129. const CGTownInstance *t = h->visitedTown;
  130. return sptr (Goals::BuildThis(BuildingID::GRAIL, t));
  131. }
  132. else
  133. {
  134. auto towns = cb->getTownsInfo();
  135. towns.erase(boost::remove_if(towns,
  136. [](const CGTownInstance *t) -> bool
  137. {
  138. return vstd::contains(t->forbiddenBuildings, BuildingID::GRAIL);
  139. }),
  140. towns.end());
  141. boost::sort(towns, isCloser);
  142. if(towns.size())
  143. {
  144. return sptr (Goals::VisitTile(towns.front()->visitablePos()).sethero(h));
  145. }
  146. }
  147. }
  148. double ratio = 0;
  149. int3 grailPos = cb->getGrailPos(ratio);
  150. if(ratio > 0.99)
  151. {
  152. return sptr (Goals::DigAtTile(grailPos));
  153. } //TODO: use FIND_OBJ
  154. else if(const CGObjectInstance * obj = ai->getUnvisitedObj(objWithID<Obj::OBELISK>)) //there are unvisited Obelisks
  155. {
  156. return sptr (Goals::GetObj(obj->id.getNum()));
  157. }
  158. else
  159. return sptr (Goals::Explore());
  160. }
  161. break;
  162. case EVictoryConditionType::CAPTURECITY:
  163. return sptr (Goals::GetObj(vc.obj->id.getNum()));
  164. case EVictoryConditionType::GATHERRESOURCE:
  165. return sptr (Goals::CollectRes(static_cast<Res::ERes>(vc.objectId), vc.count));
  166. //TODO mines? piles? marketplace?
  167. //save?
  168. break;
  169. case EVictoryConditionType::GATHERTROOP:
  170. return sptr (Goals::GatherTroops(vc.objectId, vc.count));
  171. break;
  172. case EVictoryConditionType::TAKEDWELLINGS:
  173. break;
  174. case EVictoryConditionType::TAKEMINES:
  175. break;
  176. case EVictoryConditionType::TRANSPORTITEM:
  177. break;
  178. case EVictoryConditionType::WINSTANDARD:
  179. return sptr (Goals::Conquer());
  180. default:
  181. assert(0);
  182. }
  183. return sptr (Goals::Invalid());
  184. }
  185. TSubgoal FindObj::whatToDoToAchieve()
  186. {
  187. const CGObjectInstance * o = nullptr;
  188. if (resID > -1) //specified
  189. {
  190. for(const CGObjectInstance *obj : ai->visitableObjs)
  191. {
  192. if(obj->ID == objid && obj->subID == resID)
  193. {
  194. o = obj;
  195. break; //TODO: consider multiple objects and choose best
  196. }
  197. }
  198. }
  199. else
  200. {
  201. for(const CGObjectInstance *obj : ai->visitableObjs)
  202. {
  203. if(obj->ID == objid)
  204. {
  205. o = obj;
  206. break; //TODO: consider multiple objects and choose best
  207. }
  208. }
  209. }
  210. if (o && isReachable(o)) //we don't use isAccessibleForHero as we don't know which hero it is
  211. return sptr (Goals::GetObj(o->id.getNum()));
  212. else
  213. return sptr (Goals::Explore());
  214. }
  215. float FindObj::importanceWhenLocked() const
  216. {
  217. return 1; //we will probably fins it anyway, someday
  218. }
  219. std::string GetObj::completeMessage() const
  220. {
  221. return "hero " + hero.get()->name + " captured Object ID = " + boost::lexical_cast<std::string>(objid);
  222. }
  223. TSubgoal GetObj::whatToDoToAchieve()
  224. {
  225. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(objid));
  226. if(!obj)
  227. return sptr (Goals::Explore());
  228. int3 pos = obj->visitablePos();
  229. return sptr (Goals::VisitTile(pos).sethero(hero)); //we must visit object with same hero, if any
  230. }
  231. float GetObj::importanceWhenLocked() const
  232. {
  233. return 3;
  234. }
  235. bool GetObj::fulfillsMe (shared_ptr<VisitTile> goal)
  236. {
  237. if (cb->getObj(ObjectInstanceID(objid))->visitablePos() == goal->tile)
  238. return true;
  239. else
  240. return false;
  241. }
  242. std::string VisitHero::completeMessage() const
  243. {
  244. return "hero " + hero.get()->name + " visited hero " + boost::lexical_cast<std::string>(objid);
  245. }
  246. TSubgoal VisitHero::whatToDoToAchieve()
  247. {
  248. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(objid));
  249. if(!obj)
  250. return sptr (Goals::Explore());
  251. int3 pos = obj->visitablePos();
  252. if (hero && ai->isAccessibleForHero(pos, hero, true) && isSafeToVisit(hero, pos)) //enemy heroes can get reinforcements
  253. {
  254. if (hero->pos == pos)
  255. logAi->errorStream() << "Hero " << hero.name << " tries to visit himself.";
  256. else
  257. {
  258. settile(pos).setisElementar(true);
  259. return sptr (*this);
  260. }
  261. }
  262. return sptr (Goals::Invalid());
  263. }
  264. float VisitHero::importanceWhenLocked() const
  265. {
  266. return 4;
  267. }
  268. bool VisitHero::fulfillsMe (shared_ptr<VisitTile> goal)
  269. {
  270. if (cb->getObj(ObjectInstanceID(objid))->visitablePos() == goal->tile)
  271. return true;
  272. else
  273. return false;
  274. }
  275. TSubgoal GetArtOfType::whatToDoToAchieve()
  276. {
  277. TSubgoal alternativeWay = CGoal::lookForArtSmart(aid); //TODO: use
  278. if(alternativeWay->invalid())
  279. return sptr (Goals::FindObj(Obj::ARTIFACT, aid));
  280. return sptr (Goals::Invalid());
  281. }
  282. float GetArtOfType::importanceWhenLocked() const
  283. {
  284. return 2;
  285. }
  286. TSubgoal ClearWayTo::whatToDoToAchieve()
  287. {
  288. assert(tile.x >= 0); //set tile
  289. if(!cb->isVisible(tile))
  290. {
  291. logAi->errorStream() << "Clear way should be used with visible tiles!";
  292. return sptr (Goals::Explore());
  293. }
  294. HeroPtr h = hero ? hero : ai->primaryHero();
  295. if(!h)
  296. return sptr (Goals::RecruitHero());
  297. cb->setSelection(*h);
  298. SectorMap sm;
  299. bool dropToFile = false;
  300. if(dropToFile) //for debug purposes
  301. sm.write("test.txt");
  302. int3 tileToHit = sm.firstTileToGet(h, tile);
  303. //if(isSafeToVisit(h, tileToHit))
  304. if(isBlockedBorderGate(tileToHit))
  305. { //FIXME: this way we'll not visit gate and activate quest :?
  306. return sptr (Goals::FindObj (Obj::KEYMASTER, cb->getTile(tileToHit)->visitableObjects.back()->subID));
  307. }
  308. //FIXME: this code shouldn't be necessary
  309. if(tileToHit == tile)
  310. {
  311. logAi->errorStream() << boost::format("Very strange, tile to hit is %s and tile is also %s, while hero %s is at %s\n")
  312. % tileToHit % tile % h->name % h->visitablePos();
  313. throw cannotFulfillGoalException("Retrieving first tile to hit failed (probably)!");
  314. }
  315. auto topObj = backOrNull(cb->getVisitableObjs(tileToHit));
  316. if(topObj && topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES)
  317. {
  318. std::string problem = boost::str(boost::format("%s stands in the way of %s.\n") % topObj->getHoverText() % h->getHoverText());
  319. throw cannotFulfillGoalException(problem);
  320. }
  321. return sptr (Goals::VisitTile(tileToHit).sethero(h));
  322. //FIXME:: attempts to visit completely unreachable tile with hero results in stall
  323. //TODO czy istnieje lepsza droga?
  324. throw cannotFulfillGoalException("Cannot reach given tile!"); //how and when could this be used?
  325. }
  326. float ClearWayTo::importanceWhenLocked() const
  327. {
  328. return 5;
  329. }
  330. std::string Explore::completeMessage() const
  331. {
  332. return "Hero " + hero.get()->name + " completed exploration";
  333. };
  334. TSubgoal Explore::whatToDoToAchieve()
  335. {
  336. auto ret = fh->chooseSolution(getAllPossibleSubgoals());
  337. if (hero) //use best step for this hero
  338. return ret;
  339. else
  340. {
  341. if (ret->hero.get(true))
  342. return sptr (sethero(ret->hero.h).setisAbstract(true)); //choose this hero and then continue with him
  343. else
  344. return ret; //other solutions, like buying hero from tavern
  345. }
  346. };
  347. TGoalVec Explore::getAllPossibleSubgoals()
  348. {
  349. TGoalVec ret;
  350. std::vector<HeroPtr> heroes;
  351. if (hero)
  352. heroes.push_back(hero);
  353. else
  354. {
  355. heroes = ai->getUnblockedHeroes();
  356. erase_if (heroes, [](const HeroPtr h)
  357. {
  358. return !h->movement; //saves time, immobile heroes are useless anyway
  359. });
  360. }
  361. //try to use buildings that uncover map
  362. std::vector<const CGObjectInstance *> objs;
  363. for (auto obj : ai->visitableObjs)
  364. {
  365. if (!vstd::contains(ai->alreadyVisited, obj))
  366. {
  367. switch (obj->ID.num)
  368. {
  369. case Obj::REDWOOD_OBSERVATORY:
  370. case Obj::PILLAR_OF_FIRE:
  371. case Obj::CARTOGRAPHER:
  372. case Obj::SUBTERRANEAN_GATE: //TODO: check ai->knownSubterraneanGates
  373. objs.push_back (obj);
  374. }
  375. }
  376. }
  377. for (auto h : heroes)
  378. {
  379. for (auto obj : objs) //double loop, performance risk?
  380. {
  381. if (ai->isAccessibleForHero(obj->visitablePos(), h) && isSafeToVisit(h, obj->visitablePos()))
  382. {
  383. ret.push_back (sptr (Goals::VisitTile(obj->visitablePos()).sethero(h)));
  384. }
  385. }
  386. int3 t = whereToExplore(h);
  387. if (cb->isInTheMap(t)) //valid tile was found - could be invalid (none)
  388. ret.push_back (sptr (Goals::VisitTile(t).sethero(h)));
  389. }
  390. if (!hero && ai->canRecruitAnyHero())//if hero is assigned to that goal, no need to buy another one yet
  391. ret.push_back (sptr(Goals::RecruitHero()));
  392. if (ret.empty())
  393. throw cannotFulfillGoalException("Cannot explore - no possible ways found!");
  394. return ret;
  395. };
  396. float Explore::importanceWhenLocked() const
  397. {
  398. return 1; //exploration is natural and lowpriority process
  399. }
  400. TSubgoal RecruitHero::whatToDoToAchieve()
  401. {
  402. const CGTownInstance *t = ai->findTownWithTavern();
  403. if(!t)
  404. return sptr (Goals::BuildThis(BuildingID::TAVERN));
  405. if(cb->getResourceAmount(Res::GOLD) < HERO_GOLD_COST)
  406. return sptr (Goals::CollectRes(Res::GOLD, HERO_GOLD_COST));
  407. return iAmElementar();
  408. }
  409. std::string VisitTile::completeMessage() const
  410. {
  411. return "Hero " + hero.get()->name + " visited tile " + tile();
  412. }
  413. TSubgoal VisitTile::whatToDoToAchieve()
  414. {
  415. auto ret = fh->chooseSolution(getAllPossibleSubgoals());
  416. if (ret->hero)
  417. {
  418. if (isSafeToVisit(ret->hero, tile))
  419. {
  420. ret->setisElementar(true);
  421. return ret;
  422. }
  423. else
  424. {
  425. return sptr (Goals::GatherArmy(evaluateDanger(tile, *ret->hero) * SAFE_ATTACK_CONSTANT).sethero(ret->hero));
  426. }
  427. }
  428. return ret;
  429. }
  430. float VisitTile::importanceWhenLocked() const
  431. {
  432. return 5; //depends on a distance, but we should really reach the tile once it was selected
  433. }
  434. TGoalVec VisitTile::getAllPossibleSubgoals()
  435. {
  436. TGoalVec ret;
  437. if (!cb->isVisible(tile))
  438. ret.push_back (sptr(Goals::Explore())); //what sense does it make?
  439. else
  440. {
  441. std::vector<const CGHeroInstance *> heroes;
  442. if (hero)
  443. heroes.push_back(hero.h); //use assigned hero if any
  444. else
  445. heroes = cb->getHeroesInfo(); //use most convenient hero
  446. for (auto h : heroes)
  447. {
  448. if (ai->isAccessibleForHero(tile, h))
  449. ret.push_back (sptr(Goals::VisitTile(tile).sethero(h)));
  450. }
  451. if (ai->canRecruitAnyHero())
  452. ret.push_back (sptr(Goals::RecruitHero()));
  453. }
  454. if (ret.empty())
  455. ret.push_back (sptr(Goals::ClearWayTo(tile)));
  456. //important - at least one sub-goal must handle case which is impossible to fulfill (unreachable tile)
  457. return ret;
  458. }
  459. TSubgoal DigAtTile::whatToDoToAchieve()
  460. {
  461. const CGObjectInstance *firstObj = frontOrNull(cb->getVisitableObjs(tile));
  462. if(firstObj && firstObj->ID == Obj::HERO && firstObj->tempOwner == ai->playerID) //we have hero at dest
  463. {
  464. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(firstObj);
  465. sethero(h).setisElementar(true);
  466. return sptr (*this);
  467. }
  468. return sptr (Goals::VisitTile(tile));
  469. }
  470. float DigAtTile::importanceWhenLocked() const
  471. {
  472. return 20; //do not! interrupt tile digging
  473. }
  474. TSubgoal BuildThis::whatToDoToAchieve()
  475. {
  476. //TODO check res
  477. //look for town
  478. //prerequisites?
  479. return iAmElementar();
  480. }
  481. float BuildThis::importanceWhenLocked() const
  482. {
  483. return 5;
  484. }
  485. TSubgoal CollectRes::whatToDoToAchieve()
  486. {
  487. std::vector<const IMarket*> markets;
  488. std::vector<const CGObjectInstance*> visObjs;
  489. ai->retreiveVisitableObjs(visObjs, true);
  490. for(const CGObjectInstance *obj : visObjs)
  491. {
  492. if(const IMarket *m = IMarket::castFrom(obj, false))
  493. {
  494. if(obj->ID == Obj::TOWN && obj->tempOwner == ai->playerID && m->allowsTrade(EMarketMode::RESOURCE_RESOURCE))
  495. markets.push_back(m);
  496. else if(obj->ID == Obj::TRADING_POST) //TODO a moze po prostu test na pozwalanie handlu?
  497. markets.push_back(m);
  498. }
  499. }
  500. boost::sort(markets, [](const IMarket *m1, const IMarket *m2) -> bool
  501. {
  502. return m1->getMarketEfficiency() < m2->getMarketEfficiency();
  503. });
  504. markets.erase(boost::remove_if(markets, [](const IMarket *market) -> bool
  505. {
  506. return !(market->o->ID == Obj::TOWN && market->o->tempOwner == ai->playerID)
  507. && !ai->isAccessible(market->o->visitablePos());
  508. }),markets.end());
  509. if(!markets.size())
  510. {
  511. for(const CGTownInstance *t : cb->getTownsInfo())
  512. {
  513. if(cb->canBuildStructure(t, BuildingID::MARKETPLACE) == EBuildingState::ALLOWED)
  514. return sptr (Goals::BuildThis(BuildingID::MARKETPLACE, t));
  515. }
  516. }
  517. else
  518. {
  519. const IMarket *m = markets.back();
  520. //attempt trade at back (best prices)
  521. int howManyCanWeBuy = 0;
  522. for(Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
  523. {
  524. if(i == resID) continue;
  525. int toGive = -1, toReceive = -1;
  526. m->getOffer(i, resID, toGive, toReceive, EMarketMode::RESOURCE_RESOURCE);
  527. assert(toGive > 0 && toReceive > 0);
  528. howManyCanWeBuy += toReceive * (cb->getResourceAmount(i) / toGive);
  529. }
  530. if(howManyCanWeBuy + cb->getResourceAmount(static_cast<Res::ERes>(resID)) >= value)
  531. {
  532. auto backObj = backOrNull(cb->getVisitableObjs(m->o->visitablePos())); //it'll be a hero if we have one there; otherwise marketplace
  533. assert(backObj);
  534. if (backObj->tempOwner != ai->playerID)
  535. {
  536. return sptr (Goals::GetObj(m->o->id.getNum()));
  537. }
  538. else
  539. {
  540. return sptr (Goals::GetObj(m->o->id.getNum()).setisElementar(true));
  541. }
  542. }
  543. }
  544. return sptr (Goals::Invalid()); //FIXME: unused?
  545. }
  546. float CollectRes::importanceWhenLocked() const
  547. {
  548. return 2;
  549. }
  550. TSubgoal GatherTroops::whatToDoToAchieve()
  551. {
  552. std::vector<const CGDwelling *> dwellings;
  553. for(const CGTownInstance *t : cb->getTownsInfo())
  554. {
  555. auto creature = VLC->creh->creatures[objid];
  556. if (t->subID == creature->faction) //TODO: how to force AI to build unupgraded creatures? :O
  557. {
  558. auto creatures = vstd::tryAt(t->town->creatures, creature->level - 1);
  559. if(!creatures)
  560. continue;
  561. int upgradeNumber = vstd::find_pos(*creatures, creature->idNumber);
  562. if(upgradeNumber < 0)
  563. continue;
  564. BuildingID bid(BuildingID::DWELL_FIRST + creature->level - 1 + upgradeNumber * GameConstants::CREATURES_PER_TOWN);
  565. if (t->hasBuilt(bid)) //this assumes only creatures with dwellings are assigned to faction
  566. {
  567. dwellings.push_back(t);
  568. }
  569. else
  570. {
  571. return sptr (Goals::BuildThis(bid, t));
  572. }
  573. }
  574. }
  575. for (auto obj : ai->visitableObjs)
  576. {
  577. if (obj->ID != Obj::CREATURE_GENERATOR1) //TODO: what with other creature generators?
  578. continue;
  579. auto d = dynamic_cast<const CGDwelling *>(obj);
  580. for (auto creature : d->creatures)
  581. {
  582. if (creature.first) //there are more than 0 creatures avaliabe
  583. {
  584. for (auto type : creature.second)
  585. {
  586. if (type == objid && ai->freeResources().canAfford(VLC->creh->creatures[type]->cost))
  587. dwellings.push_back(d);
  588. }
  589. }
  590. }
  591. }
  592. if (dwellings.size())
  593. {
  594. boost::sort(dwellings, isCloser);
  595. return sptr (Goals::GetObj(dwellings.front()->id.getNum()));
  596. }
  597. else
  598. return sptr (Goals::Explore());
  599. //TODO: exchange troops between heroes
  600. }
  601. float GatherTroops::importanceWhenLocked() const
  602. {
  603. return 2;
  604. }
  605. TSubgoal Conquer::whatToDoToAchieve()
  606. {
  607. return fh->chooseSolution (getAllPossibleSubgoals());
  608. }
  609. TGoalVec Conquer::getAllPossibleSubgoals()
  610. {
  611. TGoalVec ret;
  612. std::vector<const CGObjectInstance *> objs; //here we'll gather enemy towns and heroes
  613. ai->retreiveVisitableObjs(objs);
  614. erase_if(objs, [&](const CGObjectInstance *obj)
  615. {
  616. return (obj->ID != Obj::TOWN && obj->ID != Obj::HERO && //not town/hero
  617. obj->ID != Obj::CREATURE_GENERATOR1 && obj->ID != Obj::MINE) //not dwelling or mine
  618. || cb->getPlayerRelations(ai->playerID, obj->tempOwner) != PlayerRelations::ENEMIES; //only enemy objects are interesting
  619. });
  620. erase_if(objs, [&](const CGObjectInstance *obj)
  621. {
  622. return vstd::contains (ai->reservedObjs, obj);
  623. //no need to capture same object twice
  624. });
  625. for (auto h : cb->getHeroesInfo())
  626. {
  627. for (auto obj : objs) //double loop, performance risk?
  628. {
  629. if (ai->isAccessibleForHero(obj->visitablePos(), h) && isSafeToVisit(h, obj->visitablePos()))
  630. {
  631. if (obj->ID == Obj::HERO)
  632. ret.push_back (sptr (Goals::VisitHero(obj->id.getNum()).sethero(h).setisAbstract(true)));
  633. //track enemy hero
  634. else
  635. ret.push_back (sptr (Goals::VisitTile(obj->visitablePos()).sethero(h)));
  636. }
  637. }
  638. }
  639. if (!objs.empty() && ai->canRecruitAnyHero()) //probably no point to recruit hero if we see no objects to capture
  640. ret.push_back (sptr(Goals::RecruitHero()));
  641. if (ret.empty())
  642. ret.push_back (sptr(Goals::Explore())); //we need to find an enemy
  643. return ret;
  644. }
  645. float Conquer::importanceWhenLocked() const
  646. {
  647. return 10; //defeating opponent is hig priority, always
  648. }
  649. TSubgoal Build::whatToDoToAchieve()
  650. {
  651. return iAmElementar();
  652. }
  653. float Build::importanceWhenLocked() const
  654. {
  655. return 1;
  656. }
  657. TSubgoal Invalid::whatToDoToAchieve()
  658. {
  659. return iAmElementar();
  660. }
  661. std::string GatherArmy::completeMessage() const
  662. {
  663. return "Hero " + hero.get()->name + " gathered army of value " + boost::lexical_cast<std::string>(value);
  664. };
  665. TSubgoal GatherArmy::whatToDoToAchieve()
  666. {
  667. //TODO: find hero if none set
  668. assert(hero);
  669. cb->setSelection(*hero);
  670. auto compareReinforcements = [this](const CGTownInstance *lhs, const CGTownInstance *rhs) -> bool
  671. {
  672. return howManyReinforcementsCanGet(hero, lhs) < howManyReinforcementsCanGet(hero, rhs);
  673. };
  674. std::vector<const CGTownInstance *> townsReachable;
  675. for(const CGTownInstance *t : cb->getTownsInfo())
  676. {
  677. if(!t->visitingHero && howManyReinforcementsCanGet(hero,t))
  678. {
  679. if (ai->isAccessibleForHero(t->pos, hero) && !vstd::contains (ai->townVisitsThisWeek[hero], t))
  680. townsReachable.push_back(t);
  681. }
  682. }
  683. if(townsReachable.size()) //try towns first
  684. {
  685. boost::sort(townsReachable, compareReinforcements);
  686. return sptr (Goals::VisitTile(townsReachable.back()->visitablePos()).sethero(hero));
  687. }
  688. else
  689. {
  690. if (hero == ai->primaryHero()) //we can get army from other heroes
  691. {
  692. auto otherHeroes = cb->getHeroesInfo();
  693. auto heroDummy = hero;
  694. erase_if(otherHeroes, [heroDummy](const CGHeroInstance * h)
  695. {
  696. return (h == heroDummy.h || !ai->isAccessibleForHero(heroDummy->visitablePos(), h, true) || !ai->canGetArmy(heroDummy.h, h));
  697. });
  698. if (otherHeroes.size())
  699. {
  700. boost::sort(otherHeroes, compareArmyStrength); //TODO: check if hero has at least one stack more powerful than ours? not likely to fail
  701. int primaryPath, secondaryPath;
  702. auto h = otherHeroes.back();
  703. cb->setSelection(hero.h);
  704. primaryPath = cb->getPathInfo(h->visitablePos())->turns;
  705. cb->setSelection(h);
  706. secondaryPath = cb->getPathInfo(hero->visitablePos())->turns;
  707. if (primaryPath < secondaryPath)
  708. return sptr (Goals::VisitHero(h->id.getNum()).setisAbstract(true).sethero(hero));
  709. //go to the other hero if we are faster
  710. else
  711. return sptr (Goals::VisitHero(hero->id.getNum()).setisAbstract(true).sethero(h));
  712. //let the other hero come to us
  713. }
  714. }
  715. std::vector<const CGObjectInstance *> objs; //here we'll gather all dwellings
  716. ai->retreiveVisitableObjs(objs, true);
  717. erase_if(objs, [&](const CGObjectInstance *obj)
  718. {
  719. if(obj->ID != Obj::CREATURE_GENERATOR1)
  720. return true;
  721. auto relationToOwner = cb->getPlayerRelations(obj->getOwner(), ai->playerID);
  722. if(relationToOwner == PlayerRelations::ALLIES)
  723. return true;
  724. //Use flagged dwellings only when there are available creatures that we can afford
  725. if(relationToOwner == PlayerRelations::SAME_PLAYER)
  726. {
  727. auto dwelling = dynamic_cast<const CGDwelling*>(obj);
  728. for(auto & creLevel : dwelling->creatures)
  729. {
  730. if(creLevel.first)
  731. {
  732. for(auto & creatureID : creLevel.second)
  733. {
  734. auto creature = VLC->creh->creatures[creatureID];
  735. if(ai->freeResources().canAfford(creature->cost))
  736. return false;
  737. }
  738. }
  739. }
  740. }
  741. return true;
  742. });
  743. if(objs.empty()) //no possible objects, we did eveyrthing already
  744. return sptr (Goals::Explore(hero));
  745. //TODO: check if we can recruit any creatures there, evaluate army
  746. else
  747. {
  748. boost::sort(objs, isCloser);
  749. HeroPtr h = nullptr;
  750. for(const CGObjectInstance *obj : objs)
  751. { //find safe dwelling
  752. auto pos = obj->visitablePos();
  753. if (shouldVisit (hero, obj)) //creatures fit in army
  754. h = hero;
  755. else
  756. {
  757. for(auto ourHero : cb->getHeroesInfo()) //make use of multiple heroes
  758. {
  759. if (shouldVisit(ourHero, obj))
  760. h = ourHero;
  761. }
  762. }
  763. if (h && isSafeToVisit(h, pos) && ai->isAccessibleForHero(pos, h))
  764. return sptr (Goals::VisitTile(pos).sethero(h));
  765. }
  766. }
  767. }
  768. return sptr (Goals::Explore(hero)); //find dwelling. use current hero to prevent him from doing nothing.
  769. }
  770. float GatherArmy::importanceWhenLocked() const
  771. {
  772. return 2.5;
  773. }
  774. //TSubgoal AbstractGoal::whatToDoToAchieve()
  775. //{
  776. // logAi->debugStream() << boost::format("Decomposing goal of type %s") % name();
  777. // return sptr (Goals::Explore());
  778. //}
  779. TSubgoal AbstractGoal::goVisitOrLookFor(const CGObjectInstance *obj)
  780. {
  781. if(obj)
  782. return sptr (Goals::GetObj(obj->id.getNum()));
  783. else
  784. return sptr (Goals::Explore());
  785. }
  786. TSubgoal AbstractGoal::lookForArtSmart(int aid)
  787. {
  788. return sptr (Goals::Invalid());
  789. }
  790. bool AbstractGoal::invalid() const
  791. {
  792. return goalType == INVALID;
  793. }
  794. void AbstractGoal::accept (VCAI * ai)
  795. {
  796. ai->tryRealize(*this);
  797. }
  798. template<typename T>
  799. void CGoal<T>::accept (VCAI * ai)
  800. {
  801. ai->tryRealize(static_cast<T&>(*this)); //casting enforces template instantiation
  802. }
  803. float AbstractGoal::accept (FuzzyHelper * f)
  804. {
  805. return f->evaluate(*this);
  806. }
  807. template<typename T>
  808. float CGoal<T>::accept (FuzzyHelper * f)
  809. {
  810. return f->evaluate(static_cast<T&>(*this)); //casting enforces template instantiation
  811. }