Goals.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  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));
  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. assert (hero->pos != pos); //don't try to visit yourself
  255. settile(pos).setisElementar(true);
  256. return sptr (*this);
  257. }
  258. return sptr (Goals::Invalid());
  259. }
  260. float VisitHero::importanceWhenLocked() const
  261. {
  262. return 4;
  263. }
  264. bool VisitHero::fulfillsMe (shared_ptr<VisitTile> goal)
  265. {
  266. if (cb->getObj(ObjectInstanceID(objid))->visitablePos() == goal->tile)
  267. return true;
  268. else
  269. return false;
  270. }
  271. TSubgoal GetArtOfType::whatToDoToAchieve()
  272. {
  273. TSubgoal alternativeWay = CGoal::lookForArtSmart(aid); //TODO: use
  274. if(alternativeWay->invalid())
  275. return sptr (Goals::FindObj(Obj::ARTIFACT, aid));
  276. return sptr (Goals::Invalid());
  277. }
  278. float GetArtOfType::importanceWhenLocked() const
  279. {
  280. return 2;
  281. }
  282. TSubgoal ClearWayTo::whatToDoToAchieve()
  283. {
  284. assert(tile.x >= 0); //set tile
  285. if(!cb->isVisible(tile))
  286. {
  287. logAi->errorStream() << "Clear way should be used with visible tiles!";
  288. return sptr (Goals::Explore());
  289. }
  290. HeroPtr h = hero ? hero : ai->primaryHero();
  291. if(!h)
  292. return sptr (Goals::RecruitHero());
  293. cb->setSelection(*h);
  294. SectorMap sm;
  295. bool dropToFile = false;
  296. if(dropToFile) //for debug purposes
  297. sm.write("test.txt");
  298. int3 tileToHit = sm.firstTileToGet(h, tile);
  299. //if(isSafeToVisit(h, tileToHit))
  300. if(isBlockedBorderGate(tileToHit))
  301. { //FIXME: this way we'll not visit gate and activate quest :?
  302. return sptr (Goals::FindObj (Obj::KEYMASTER, cb->getTile(tileToHit)->visitableObjects.back()->subID));
  303. }
  304. //FIXME: this code shouldn't be necessary
  305. if(tileToHit == tile)
  306. {
  307. logAi->errorStream() << boost::format("Very strange, tile to hit is %s and tile is also %s, while hero %s is at %s\n")
  308. % tileToHit % tile % h->name % h->visitablePos();
  309. throw cannotFulfillGoalException("Retrieving first tile to hit failed (probably)!");
  310. }
  311. auto topObj = backOrNull(cb->getVisitableObjs(tileToHit));
  312. if(topObj && topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES)
  313. {
  314. std::string problem = boost::str(boost::format("%s stands in the way of %s.\n") % topObj->getHoverText() % h->getHoverText());
  315. throw cannotFulfillGoalException(problem);
  316. }
  317. return sptr (Goals::VisitTile(tileToHit).sethero(h));
  318. //FIXME:: attempts to visit completely unreachable tile with hero results in stall
  319. //TODO czy istnieje lepsza droga?
  320. throw cannotFulfillGoalException("Cannot reach given tile!"); //how and when could this be used?
  321. }
  322. float ClearWayTo::importanceWhenLocked() const
  323. {
  324. return 5;
  325. }
  326. std::string Explore::completeMessage() const
  327. {
  328. return "Hero " + hero.get()->name + " completed exploration";
  329. };
  330. TSubgoal Explore::whatToDoToAchieve()
  331. {
  332. auto ret = fh->chooseSolution(getAllPossibleSubgoals());
  333. if (hero) //use best step for this hero
  334. return ret;
  335. else
  336. {
  337. if (ret->hero.get(true))
  338. return sptr (sethero(ret->hero.h).setisAbstract(true)); //choose this hero and then continue with him
  339. else
  340. return ret; //other solutions, like buying hero from tavern
  341. }
  342. };
  343. TGoalVec Explore::getAllPossibleSubgoals()
  344. {
  345. TGoalVec ret;
  346. std::vector<HeroPtr> heroes;
  347. if (hero)
  348. heroes.push_back(hero);
  349. else
  350. {
  351. heroes = ai->getUnblockedHeroes();
  352. erase_if (heroes, [](const HeroPtr h)
  353. {
  354. return !h->movement; //saves time, immobile heroes are useless anyway
  355. });
  356. }
  357. auto objs = ai->visitableObjs; //try to use buildings that uncover map
  358. erase_if(objs, [&](const CGObjectInstance *obj) -> bool
  359. {
  360. if (vstd::contains(ai->alreadyVisited, obj))
  361. return true;
  362. switch (obj->ID.num)
  363. {
  364. case Obj::REDWOOD_OBSERVATORY:
  365. case Obj::PILLAR_OF_FIRE:
  366. case Obj::CARTOGRAPHER:
  367. case Obj::SUBTERRANEAN_GATE: //TODO: check ai->knownSubterraneanGates
  368. //case Obj::MONOLITH1:
  369. //case obj::MONOLITH2:
  370. //case obj::MONOLITH3:
  371. //case Obj::WHIRLPOOL:
  372. return false; //do not erase
  373. break;
  374. default:
  375. return true;
  376. }
  377. });
  378. for (auto h : heroes)
  379. {
  380. for (auto obj : objs) //double loop, performance risk?
  381. {
  382. if (ai->isAccessibleForHero(obj->visitablePos(), h) && isSafeToVisit(h, obj->visitablePos()))
  383. {
  384. ret.push_back (sptr (Goals::VisitTile(obj->visitablePos()).sethero(h)));
  385. }
  386. }
  387. int3 t = whereToExplore(h);
  388. if (t.z != -1) //no safe tile to explore - we need to break!
  389. ret.push_back (sptr (Goals::VisitTile(t).sethero(h)));
  390. }
  391. if (!hero && ai->canRecruitAnyHero())//if hero is assigned to that goal, no need to buy another one yet
  392. ret.push_back (sptr(Goals::RecruitHero()));
  393. if (ret.empty())
  394. throw cannotFulfillGoalException("Cannot explore - no possible ways found!");
  395. return ret;
  396. };
  397. float Explore::importanceWhenLocked() const
  398. {
  399. return 1; //exploration is natural and lowpriority process
  400. }
  401. TSubgoal RecruitHero::whatToDoToAchieve()
  402. {
  403. const CGTownInstance *t = ai->findTownWithTavern();
  404. if(!t)
  405. return sptr (Goals::BuildThis(BuildingID::TAVERN));
  406. if(cb->getResourceAmount(Res::GOLD) < HERO_GOLD_COST)
  407. return sptr (Goals::CollectRes(Res::GOLD, HERO_GOLD_COST));
  408. return iAmElementar();
  409. }
  410. std::string VisitTile::completeMessage() const
  411. {
  412. return "Hero " + hero.get()->name + " visited tile " + tile();
  413. }
  414. TSubgoal VisitTile::whatToDoToAchieve()
  415. {
  416. auto ret = fh->chooseSolution(getAllPossibleSubgoals());
  417. if (ret->hero)
  418. {
  419. if (isSafeToVisit(ret->hero, tile))
  420. {
  421. ret->setisElementar(true);
  422. return ret;
  423. }
  424. else
  425. {
  426. return sptr (Goals::GatherArmy(evaluateDanger(tile, *ret->hero) * SAFE_ATTACK_CONSTANT).sethero(ret->hero));
  427. }
  428. }
  429. return ret;
  430. }
  431. float VisitTile::importanceWhenLocked() const
  432. {
  433. return 5; //depends on a distance, but we should really reach the tile once it was selected
  434. }
  435. TGoalVec VisitTile::getAllPossibleSubgoals()
  436. {
  437. TGoalVec ret;
  438. if (!cb->isVisible(tile))
  439. ret.push_back (sptr(Goals::Explore())); //what sense does it make?
  440. else
  441. {
  442. std::vector<const CGHeroInstance *> heroes;
  443. if (hero)
  444. heroes.push_back(hero.h); //use assigned hero if any
  445. else
  446. heroes = cb->getHeroesInfo(); //use most convenient hero
  447. for (auto h : heroes)
  448. {
  449. if (ai->isAccessibleForHero(tile, h))
  450. ret.push_back (sptr(Goals::VisitTile(tile).sethero(h)));
  451. }
  452. if (ai->canRecruitAnyHero())
  453. ret.push_back (sptr(Goals::RecruitHero()));
  454. }
  455. if (ret.empty())
  456. ret.push_back (sptr(Goals::ClearWayTo(tile)));
  457. //important - at least one sub-goal must handle case which is impossible to fulfill (unreachable tile)
  458. return ret;
  459. }
  460. TSubgoal DigAtTile::whatToDoToAchieve()
  461. {
  462. const CGObjectInstance *firstObj = frontOrNull(cb->getVisitableObjs(tile));
  463. if(firstObj && firstObj->ID == Obj::HERO && firstObj->tempOwner == ai->playerID) //we have hero at dest
  464. {
  465. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(firstObj);
  466. sethero(h).setisElementar(true);
  467. return sptr (*this);
  468. }
  469. return sptr (Goals::VisitTile(tile));
  470. }
  471. float DigAtTile::importanceWhenLocked() const
  472. {
  473. return 20; //do not! interrupt tile digging
  474. }
  475. TSubgoal BuildThis::whatToDoToAchieve()
  476. {
  477. //TODO check res
  478. //look for town
  479. //prerequisites?
  480. return iAmElementar();
  481. }
  482. float BuildThis::importanceWhenLocked() const
  483. {
  484. return 5;
  485. }
  486. TSubgoal CollectRes::whatToDoToAchieve()
  487. {
  488. std::vector<const IMarket*> markets;
  489. std::vector<const CGObjectInstance*> visObjs;
  490. ai->retreiveVisitableObjs(visObjs, true);
  491. for(const CGObjectInstance *obj : visObjs)
  492. {
  493. if(const IMarket *m = IMarket::castFrom(obj, false))
  494. {
  495. if(obj->ID == Obj::TOWN && obj->tempOwner == ai->playerID && m->allowsTrade(EMarketMode::RESOURCE_RESOURCE))
  496. markets.push_back(m);
  497. else if(obj->ID == Obj::TRADING_POST) //TODO a moze po prostu test na pozwalanie handlu?
  498. markets.push_back(m);
  499. }
  500. }
  501. boost::sort(markets, [](const IMarket *m1, const IMarket *m2) -> bool
  502. {
  503. return m1->getMarketEfficiency() < m2->getMarketEfficiency();
  504. });
  505. markets.erase(boost::remove_if(markets, [](const IMarket *market) -> bool
  506. {
  507. return !(market->o->ID == Obj::TOWN && market->o->tempOwner == ai->playerID)
  508. && !ai->isAccessible(market->o->visitablePos());
  509. }),markets.end());
  510. if(!markets.size())
  511. {
  512. for(const CGTownInstance *t : cb->getTownsInfo())
  513. {
  514. if(cb->canBuildStructure(t, BuildingID::MARKETPLACE) == EBuildingState::ALLOWED)
  515. return sptr (Goals::BuildThis(BuildingID::MARKETPLACE, t));
  516. }
  517. }
  518. else
  519. {
  520. const IMarket *m = markets.back();
  521. //attempt trade at back (best prices)
  522. int howManyCanWeBuy = 0;
  523. for(Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
  524. {
  525. if(i == resID) continue;
  526. int toGive = -1, toReceive = -1;
  527. m->getOffer(i, resID, toGive, toReceive, EMarketMode::RESOURCE_RESOURCE);
  528. assert(toGive > 0 && toReceive > 0);
  529. howManyCanWeBuy += toReceive * (cb->getResourceAmount(i) / toGive);
  530. }
  531. if(howManyCanWeBuy + cb->getResourceAmount(static_cast<Res::ERes>(resID)) >= value)
  532. {
  533. auto backObj = backOrNull(cb->getVisitableObjs(m->o->visitablePos())); //it'll be a hero if we have one there; otherwise marketplace
  534. assert(backObj);
  535. if (backObj->tempOwner != ai->playerID)
  536. {
  537. return sptr (Goals::GetObj(m->o->id.getNum()));
  538. }
  539. else
  540. {
  541. return sptr (Goals::GetObj(m->o->id.getNum()).setisElementar(true));
  542. }
  543. }
  544. }
  545. return sptr (Goals::Invalid()); //FIXME: unused?
  546. }
  547. float CollectRes::importanceWhenLocked() const
  548. {
  549. return 2;
  550. }
  551. TSubgoal GatherTroops::whatToDoToAchieve()
  552. {
  553. std::vector<const CGDwelling *> dwellings;
  554. for(const CGTownInstance *t : cb->getTownsInfo())
  555. {
  556. auto creature = VLC->creh->creatures[objid];
  557. if (t->subID == creature->faction) //TODO: how to force AI to build unupgraded creatures? :O
  558. {
  559. auto creatures = vstd::tryAt(t->town->creatures, creature->level - 1);
  560. if(!creatures)
  561. continue;
  562. int upgradeNumber = vstd::find_pos(*creatures, creature->idNumber);
  563. if(upgradeNumber < 0)
  564. continue;
  565. BuildingID bid(BuildingID::DWELL_FIRST + creature->level - 1 + upgradeNumber * GameConstants::CREATURES_PER_TOWN);
  566. if (t->hasBuilt(bid)) //this assumes only creatures with dwellings are assigned to faction
  567. {
  568. dwellings.push_back(t);
  569. }
  570. else
  571. {
  572. return sptr (Goals::BuildThis(bid, t));
  573. }
  574. }
  575. }
  576. for (auto obj : ai->visitableObjs)
  577. {
  578. if (obj->ID != Obj::CREATURE_GENERATOR1) //TODO: what with other creature generators?
  579. continue;
  580. auto d = dynamic_cast<const CGDwelling *>(obj);
  581. for (auto creature : d->creatures)
  582. {
  583. if (creature.first) //there are more than 0 creatures avaliabe
  584. {
  585. for (auto type : creature.second)
  586. {
  587. if (type == objid && ai->freeResources().canAfford(VLC->creh->creatures[type]->cost))
  588. dwellings.push_back(d);
  589. }
  590. }
  591. }
  592. }
  593. if (dwellings.size())
  594. {
  595. boost::sort(dwellings, isCloser);
  596. return sptr (Goals::GetObj(dwellings.front()->id.getNum()));
  597. }
  598. else
  599. return sptr (Goals::Explore());
  600. //TODO: exchange troops between heroes
  601. }
  602. float GatherTroops::importanceWhenLocked() const
  603. {
  604. return 2;
  605. }
  606. TSubgoal Conquer::whatToDoToAchieve()
  607. {
  608. return fh->chooseSolution (getAllPossibleSubgoals());
  609. }
  610. TGoalVec Conquer::getAllPossibleSubgoals()
  611. {
  612. TGoalVec ret;
  613. std::vector<const CGObjectInstance *> objs; //here we'll gather enemy towns and heroes
  614. ai->retreiveVisitableObjs(objs);
  615. erase_if(objs, [&](const CGObjectInstance *obj)
  616. {
  617. return (obj->ID != Obj::TOWN && obj->ID != Obj::HERO && //not town/hero
  618. obj->ID != Obj::CREATURE_GENERATOR1 && obj->ID != Obj::MINE) //not dwelling or mine
  619. || cb->getPlayerRelations(ai->playerID, obj->tempOwner) != PlayerRelations::ENEMIES; //only enemy objects are interesting
  620. });
  621. erase_if(objs, [&](const CGObjectInstance *obj)
  622. {
  623. return vstd::contains (ai->reservedObjs, obj);
  624. //no need to capture same object twice
  625. });
  626. for (auto h : cb->getHeroesInfo())
  627. {
  628. for (auto obj : objs) //double loop, performance risk?
  629. {
  630. if (ai->isAccessibleForHero(obj->visitablePos(), h) && isSafeToVisit(h, obj->visitablePos()))
  631. {
  632. if (obj->ID == Obj::HERO)
  633. ret.push_back (sptr (Goals::VisitHero(obj->id.getNum()).sethero(h).setisAbstract(true)));
  634. //track enemy hero
  635. else
  636. ret.push_back (sptr (Goals::VisitTile(obj->visitablePos()).sethero(h)));
  637. }
  638. }
  639. }
  640. if (!objs.empty() && ai->canRecruitAnyHero()) //probably no point to recruit hero if we see no objects to capture
  641. ret.push_back (sptr(Goals::RecruitHero()));
  642. if (ret.empty())
  643. ret.push_back (sptr(Goals::Explore())); //we need to find an enemy
  644. return ret;
  645. }
  646. float Conquer::importanceWhenLocked() const
  647. {
  648. return 10; //defeating opponent is hig priority, always
  649. }
  650. TSubgoal Build::whatToDoToAchieve()
  651. {
  652. return iAmElementar();
  653. }
  654. float Build::importanceWhenLocked() const
  655. {
  656. return 1;
  657. }
  658. TSubgoal Invalid::whatToDoToAchieve()
  659. {
  660. return iAmElementar();
  661. }
  662. std::string GatherArmy::completeMessage() const
  663. {
  664. return "Hero " + hero.get()->name + " gathered army of value " + boost::lexical_cast<std::string>(value);
  665. };
  666. TSubgoal GatherArmy::whatToDoToAchieve()
  667. {
  668. //TODO: find hero if none set
  669. assert(hero);
  670. cb->setSelection(*hero);
  671. auto compareReinforcements = [this](const CGTownInstance *lhs, const CGTownInstance *rhs) -> bool
  672. {
  673. return howManyReinforcementsCanGet(hero, lhs) < howManyReinforcementsCanGet(hero, rhs);
  674. };
  675. std::vector<const CGTownInstance *> townsReachable;
  676. for(const CGTownInstance *t : cb->getTownsInfo())
  677. {
  678. if(!t->visitingHero && howManyReinforcementsCanGet(hero,t))
  679. {
  680. if (ai->isAccessibleForHero(t->pos, hero) && !vstd::contains (ai->townVisitsThisWeek[hero], t))
  681. townsReachable.push_back(t);
  682. }
  683. }
  684. if(townsReachable.size()) //try towns first
  685. {
  686. boost::sort(townsReachable, compareReinforcements);
  687. return sptr (Goals::VisitTile(townsReachable.back()->visitablePos()).sethero(hero));
  688. }
  689. else
  690. {
  691. if (hero == ai->primaryHero()) //we can get army from other heroes
  692. {
  693. auto otherHeroes = cb->getHeroesInfo();
  694. auto heroDummy = hero;
  695. erase_if(otherHeroes, [heroDummy](const CGHeroInstance * h)
  696. {
  697. return (h == heroDummy.h || !ai->isAccessibleForHero(heroDummy->visitablePos(), h, true) || !ai->canGetArmy(heroDummy.h, h));
  698. });
  699. if (otherHeroes.size())
  700. {
  701. boost::sort(otherHeroes, compareArmyStrength); //TODO: check if hero has at least one stack more powerful than ours? not likely to fail
  702. int primaryPath, secondaryPath;
  703. auto h = otherHeroes.back();
  704. cb->setSelection(hero.h);
  705. primaryPath = cb->getPathInfo(h->visitablePos())->turns;
  706. cb->setSelection(h);
  707. secondaryPath = cb->getPathInfo(hero->visitablePos())->turns;
  708. if (primaryPath < secondaryPath)
  709. return sptr (Goals::VisitHero(h->id.getNum()).setisAbstract(true).sethero(hero));
  710. //go to the other hero if we are faster
  711. else
  712. return sptr (Goals::VisitHero(hero->id.getNum()).setisAbstract(true).sethero(h));
  713. //let the other hero come to us
  714. }
  715. }
  716. std::vector<const CGObjectInstance *> objs; //here we'll gather all dwellings
  717. ai->retreiveVisitableObjs(objs, true);
  718. erase_if(objs, [&](const CGObjectInstance *obj)
  719. {
  720. if(obj->ID != Obj::CREATURE_GENERATOR1)
  721. return true;
  722. auto relationToOwner = cb->getPlayerRelations(obj->getOwner(), ai->playerID);
  723. if(relationToOwner == PlayerRelations::ALLIES)
  724. return true;
  725. //Use flagged dwellings only when there are available creatures that we can afford
  726. if(relationToOwner == PlayerRelations::SAME_PLAYER)
  727. {
  728. auto dwelling = dynamic_cast<const CGDwelling*>(obj);
  729. for(auto & creLevel : dwelling->creatures)
  730. {
  731. if(creLevel.first)
  732. {
  733. for(auto & creatureID : creLevel.second)
  734. {
  735. auto creature = VLC->creh->creatures[creatureID];
  736. if(ai->freeResources().canAfford(creature->cost))
  737. return false;
  738. }
  739. }
  740. }
  741. }
  742. return true;
  743. });
  744. if(objs.empty()) //no possible objects, we did eveyrthing already
  745. return sptr (Goals::Explore(hero));
  746. //TODO: check if we can recruit any creatures there, evaluate army
  747. else
  748. {
  749. boost::sort(objs, isCloser);
  750. HeroPtr h = nullptr;
  751. for(const CGObjectInstance *obj : objs)
  752. { //find safe dwelling
  753. auto pos = obj->visitablePos();
  754. if (shouldVisit (hero, obj)) //creatures fit in army
  755. h = hero;
  756. else
  757. {
  758. for(auto ourHero : cb->getHeroesInfo()) //make use of multiple heroes
  759. {
  760. if (shouldVisit(ourHero, obj))
  761. h = ourHero;
  762. }
  763. }
  764. if (h && isSafeToVisit(h, pos) && ai->isAccessibleForHero(pos, h))
  765. return sptr (Goals::VisitTile(pos).sethero(h));
  766. }
  767. }
  768. }
  769. return sptr (Goals::Explore(hero)); //find dwelling. use current hero to prevent him from doing nothing.
  770. }
  771. float GatherArmy::importanceWhenLocked() const
  772. {
  773. return 2.5;
  774. }
  775. //TSubgoal AbstractGoal::whatToDoToAchieve()
  776. //{
  777. // logAi->debugStream() << boost::format("Decomposing goal of type %s") % name();
  778. // return sptr (Goals::Explore());
  779. //}
  780. TSubgoal AbstractGoal::goVisitOrLookFor(const CGObjectInstance *obj)
  781. {
  782. if(obj)
  783. return sptr (Goals::GetObj(obj->id.getNum()));
  784. else
  785. return sptr (Goals::Explore());
  786. }
  787. TSubgoal AbstractGoal::lookForArtSmart(int aid)
  788. {
  789. return sptr (Goals::Invalid());
  790. }
  791. bool AbstractGoal::invalid() const
  792. {
  793. return goalType == INVALID;
  794. }
  795. void AbstractGoal::accept (VCAI * ai)
  796. {
  797. ai->tryRealize(*this);
  798. }
  799. template<typename T>
  800. void CGoal<T>::accept (VCAI * ai)
  801. {
  802. ai->tryRealize(static_cast<T&>(*this)); //casting enforces template instantiation
  803. }
  804. float AbstractGoal::accept (FuzzyHelper * f)
  805. {
  806. return f->evaluate(*this);
  807. }
  808. template<typename T>
  809. float CGoal<T>::accept (FuzzyHelper * f)
  810. {
  811. return f->evaluate(static_cast<T&>(*this)); //casting enforces template instantiation
  812. }