Goals.cpp 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  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. SectorMap sm(h);
  378. int3 tileToHit = sm.firstTileToGet(hero ? hero : h, tile);
  379. //if our hero is trapped, make sure we request clearing the way from OUR perspective
  380. if (!tileToHit.valid())
  381. continue;
  382. if (isBlockedBorderGate(tileToHit))
  383. { //FIXME: this way we'll not visit gate and activate quest :?
  384. ret.push_back (sptr (Goals::FindObj (Obj::KEYMASTER, cb->getTile(tileToHit)->visitableObjects.back()->subID)));
  385. }
  386. auto topObj = cb->getTopObj(tileToHit);
  387. if(topObj)
  388. {
  389. if (topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES)
  390. if (topObj != hero.get(true)) //the hero we wnat to free
  391. logAi->errorStream() << boost::format("%s stands in the way of %s") % topObj->getHoverText() % h->getHoverText();
  392. if (topObj->ID == Obj::QUEST_GUARD || topObj->ID == Obj::BORDERGUARD)
  393. {
  394. if (shouldVisit(h, topObj))
  395. {
  396. //do NOT use VISIT_TILE, as tile with quets guard can't be visited
  397. ret.push_back (sptr (Goals::GetObj(topObj->id.getNum()).sethero(h)));
  398. }
  399. else
  400. {
  401. //TODO: we should be able to return apriopriate quest here (VCAI::striveToQuest)
  402. logAi->debugStream() << "Quest guard blocks the way to " + tile();
  403. }
  404. }
  405. }
  406. else
  407. ret.push_back (sptr (Goals::VisitTile(tileToHit).sethero(h)));
  408. }
  409. if (ai->canRecruitAnyHero())
  410. ret.push_back (sptr (Goals::RecruitHero()));
  411. if (ret.empty())
  412. {
  413. logAi->warnStream() << "There is no known way to clear the way to tile " + tile();
  414. throw goalFulfilledException (sptr(*this)); //make sure asigned hero gets unlocked
  415. }
  416. return ret;
  417. }
  418. std::string Explore::completeMessage() const
  419. {
  420. return "Hero " + hero.get()->name + " completed exploration";
  421. }
  422. TSubgoal Explore::whatToDoToAchieve()
  423. {
  424. auto ret = fh->chooseSolution(getAllPossibleSubgoals());
  425. if (hero) //use best step for this hero
  426. return ret;
  427. else
  428. {
  429. if (ret->hero.get(true))
  430. return sptr (sethero(ret->hero.h).setisAbstract(true)); //choose this hero and then continue with him
  431. else
  432. return ret; //other solutions, like buying hero from tavern
  433. }
  434. }
  435. TGoalVec Explore::getAllPossibleSubgoals()
  436. {
  437. TGoalVec ret;
  438. std::vector<const CGHeroInstance *> heroes;
  439. //std::vector<HeroPtr> heroes;
  440. if (hero)
  441. //heroes.push_back(hero);
  442. heroes.push_back(hero.h);
  443. else
  444. {
  445. //heroes = ai->getUnblockedHeroes();
  446. heroes = cb->getHeroesInfo();
  447. erase_if (heroes, [](const HeroPtr h)
  448. {
  449. if (vstd::contains(ai->lockedHeroes, h))
  450. if (ai->lockedHeroes[h]->goalType == Goals::EXPLORE) //do not reassign hero who is already explorer
  451. return true;
  452. return !h->movement; //saves time, immobile heroes are useless anyway
  453. });
  454. }
  455. //try to use buildings that uncover map
  456. std::vector<const CGObjectInstance *> objs;
  457. for (auto obj : ai->visitableObjs)
  458. {
  459. if (!vstd::contains(ai->alreadyVisited, obj))
  460. {
  461. switch (obj->ID.num)
  462. {
  463. case Obj::REDWOOD_OBSERVATORY:
  464. case Obj::PILLAR_OF_FIRE:
  465. case Obj::CARTOGRAPHER:
  466. case Obj::SUBTERRANEAN_GATE: //TODO: check ai->knownSubterraneanGates
  467. objs.push_back (obj);
  468. }
  469. }
  470. }
  471. for (auto h : heroes)
  472. {
  473. SectorMap sm(h);
  474. for (auto obj : objs) //double loop, performance risk?
  475. {
  476. auto t = sm.firstTileToGet(h, obj->visitablePos()); //we assume that no more than one tile on the way is guarded
  477. ai->whatToDoToReachTile(h, t, ret);
  478. }
  479. int3 t = whereToExplore(h);
  480. if (t.valid())
  481. {
  482. ret.push_back (sptr (Goals::VisitTile(t).sethero(h)));
  483. }
  484. else if (hero.h == h || (!hero && h == ai->primaryHero().h)) //check this only ONCE, high cost
  485. {
  486. t = ai->explorationDesperate(h);
  487. ai->whatToDoToReachTile(h, t, ret);
  488. }
  489. }
  490. //we either don't have hero yet or none of heroes can explore
  491. if ((!hero || ret.empty()) && ai->canRecruitAnyHero())
  492. ret.push_back (sptr(Goals::RecruitHero()));
  493. //if (ret.empty())
  494. //{
  495. // for (auto h : heroes) //this is costly function, use only when there is no other way
  496. // {
  497. // auto t = ai->explorationDesperate (h); //we assume that no more than one tile on the way is guarded
  498. // if (t.valid())
  499. // {
  500. // if (isSafeToVisit(h, t))
  501. // {
  502. // ret.push_back (sptr (Goals::VisitTile(t).sethero(h)));
  503. // }
  504. // else
  505. // {
  506. // ret.push_back (sptr (Goals::GatherArmy(evaluateDanger(t, h)*SAFE_ATTACK_CONSTANT).
  507. // sethero(h).setisAbstract(true)));
  508. // }
  509. // }
  510. // }
  511. //}
  512. if (ret.empty())
  513. {
  514. throw goalFulfilledException (sptr(Goals::Explore().sethero(hero)));
  515. }
  516. //throw cannotFulfillGoalException("Cannot explore - no possible ways found!");
  517. return ret;
  518. }
  519. bool Explore::fulfillsMe (TSubgoal goal)
  520. {
  521. if (goal->goalType == Goals::EXPLORE)
  522. {
  523. if (goal->hero)
  524. return hero == goal->hero;
  525. else
  526. return true; //cancel ALL exploration
  527. }
  528. return false;
  529. }
  530. TSubgoal RecruitHero::whatToDoToAchieve()
  531. {
  532. const CGTownInstance *t = ai->findTownWithTavern();
  533. if(!t)
  534. return sptr (Goals::BuildThis(BuildingID::TAVERN));
  535. if(cb->getResourceAmount(Res::GOLD) < HERO_GOLD_COST)
  536. return sptr (Goals::CollectRes(Res::GOLD, HERO_GOLD_COST));
  537. return iAmElementar();
  538. }
  539. std::string VisitTile::completeMessage() const
  540. {
  541. return "Hero " + hero.get()->name + " visited tile " + tile();
  542. }
  543. TSubgoal VisitTile::whatToDoToAchieve()
  544. {
  545. auto ret = fh->chooseSolution(getAllPossibleSubgoals());
  546. if (ret->hero)
  547. {
  548. if (isSafeToVisit(ret->hero, tile) && ai->isAccessibleForHero(tile, ret->hero))
  549. {
  550. ret->setisElementar(true);
  551. return ret;
  552. }
  553. else
  554. {
  555. return sptr (Goals::GatherArmy(evaluateDanger(tile, *ret->hero) * SAFE_ATTACK_CONSTANT)
  556. .sethero(ret->hero).setisAbstract(true));
  557. }
  558. }
  559. return ret;
  560. }
  561. TGoalVec VisitTile::getAllPossibleSubgoals()
  562. {
  563. assert(cb->isInTheMap(tile));
  564. TGoalVec ret;
  565. if (!cb->isVisible(tile))
  566. ret.push_back (sptr(Goals::Explore())); //what sense does it make?
  567. else
  568. {
  569. std::vector<const CGHeroInstance *> heroes;
  570. if (hero)
  571. heroes.push_back(hero.h); //use assigned hero if any
  572. else
  573. heroes = cb->getHeroesInfo(); //use most convenient hero
  574. for (auto h : heroes)
  575. {
  576. if (ai->isAccessibleForHero(tile, h))
  577. ret.push_back (sptr(Goals::VisitTile(tile).sethero(h)));
  578. }
  579. if (ai->canRecruitAnyHero())
  580. ret.push_back (sptr(Goals::RecruitHero()));
  581. }
  582. if (ret.empty())
  583. {
  584. auto obj = frontOrNull(cb->getVisitableObjs(tile));
  585. if (obj && obj->ID == Obj::HERO && obj->tempOwner == ai->playerID) //our own hero stands on that tile
  586. ret.push_back (sptr(Goals::VisitTile(tile).sethero(dynamic_cast<const CGHeroInstance *>(obj)).setisElementar(true)));
  587. else
  588. ret.push_back (sptr(Goals::ClearWayTo(tile)));
  589. }
  590. //important - at least one sub-goal must handle case which is impossible to fulfill (unreachable tile)
  591. return ret;
  592. }
  593. TSubgoal DigAtTile::whatToDoToAchieve()
  594. {
  595. const CGObjectInstance *firstObj = frontOrNull(cb->getVisitableObjs(tile));
  596. if(firstObj && firstObj->ID == Obj::HERO && firstObj->tempOwner == ai->playerID) //we have hero at dest
  597. {
  598. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(firstObj);
  599. sethero(h).setisElementar(true);
  600. return sptr (*this);
  601. }
  602. return sptr (Goals::VisitTile(tile));
  603. }
  604. TSubgoal BuildThis::whatToDoToAchieve()
  605. {
  606. //TODO check res
  607. //look for town
  608. //prerequisites?
  609. return iAmElementar();
  610. }
  611. TSubgoal CollectRes::whatToDoToAchieve()
  612. {
  613. std::vector<const IMarket*> markets;
  614. std::vector<const CGObjectInstance*> visObjs;
  615. ai->retreiveVisitableObjs(visObjs, true);
  616. for(const CGObjectInstance *obj : visObjs)
  617. {
  618. if(const IMarket *m = IMarket::castFrom(obj, false))
  619. {
  620. if(obj->ID == Obj::TOWN && obj->tempOwner == ai->playerID && m->allowsTrade(EMarketMode::RESOURCE_RESOURCE))
  621. markets.push_back(m);
  622. else if(obj->ID == Obj::TRADING_POST) //TODO a moze po prostu test na pozwalanie handlu?
  623. markets.push_back(m);
  624. }
  625. }
  626. boost::sort(markets, [](const IMarket *m1, const IMarket *m2) -> bool
  627. {
  628. return m1->getMarketEfficiency() < m2->getMarketEfficiency();
  629. });
  630. markets.erase(boost::remove_if(markets, [](const IMarket *market) -> bool
  631. {
  632. return !(market->o->ID == Obj::TOWN && market->o->tempOwner == ai->playerID)
  633. && !ai->isAccessible(market->o->visitablePos());
  634. }),markets.end());
  635. if(!markets.size())
  636. {
  637. for(const CGTownInstance *t : cb->getTownsInfo())
  638. {
  639. if(cb->canBuildStructure(t, BuildingID::MARKETPLACE) == EBuildingState::ALLOWED)
  640. return sptr (Goals::BuildThis(BuildingID::MARKETPLACE, t));
  641. }
  642. }
  643. else
  644. {
  645. const IMarket *m = markets.back();
  646. //attempt trade at back (best prices)
  647. int howManyCanWeBuy = 0;
  648. for(Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
  649. {
  650. if(i == resID) continue;
  651. int toGive = -1, toReceive = -1;
  652. m->getOffer(i, resID, toGive, toReceive, EMarketMode::RESOURCE_RESOURCE);
  653. assert(toGive > 0 && toReceive > 0);
  654. howManyCanWeBuy += toReceive * (cb->getResourceAmount(i) / toGive);
  655. }
  656. if(howManyCanWeBuy + cb->getResourceAmount(static_cast<Res::ERes>(resID)) >= value)
  657. {
  658. auto backObj = cb->getTopObj(m->o->visitablePos()); //it'll be a hero if we have one there; otherwise marketplace
  659. assert(backObj);
  660. if (backObj->tempOwner != ai->playerID)
  661. {
  662. return sptr (Goals::GetObj(m->o->id.getNum()));
  663. }
  664. else
  665. {
  666. return sptr (Goals::GetObj(m->o->id.getNum()).setisElementar(true));
  667. }
  668. }
  669. }
  670. return sptr (setisElementar(true)); //all the conditions for trade are met
  671. }
  672. TSubgoal GatherTroops::whatToDoToAchieve()
  673. {
  674. std::vector<const CGDwelling *> dwellings;
  675. for(const CGTownInstance *t : cb->getTownsInfo())
  676. {
  677. auto creature = VLC->creh->creatures[objid];
  678. if (t->subID == creature->faction) //TODO: how to force AI to build unupgraded creatures? :O
  679. {
  680. auto creatures = vstd::tryAt(t->town->creatures, creature->level - 1);
  681. if(!creatures)
  682. continue;
  683. int upgradeNumber = vstd::find_pos(*creatures, creature->idNumber);
  684. if(upgradeNumber < 0)
  685. continue;
  686. BuildingID bid(BuildingID::DWELL_FIRST + creature->level - 1 + upgradeNumber * GameConstants::CREATURES_PER_TOWN);
  687. if (t->hasBuilt(bid)) //this assumes only creatures with dwellings are assigned to faction
  688. {
  689. dwellings.push_back(t);
  690. }
  691. else
  692. {
  693. return sptr (Goals::BuildThis(bid, t));
  694. }
  695. }
  696. }
  697. for (auto obj : ai->visitableObjs)
  698. {
  699. if (obj->ID != Obj::CREATURE_GENERATOR1) //TODO: what with other creature generators?
  700. continue;
  701. auto d = dynamic_cast<const CGDwelling *>(obj);
  702. for (auto creature : d->creatures)
  703. {
  704. if (creature.first) //there are more than 0 creatures avaliabe
  705. {
  706. for (auto type : creature.second)
  707. {
  708. if (type == objid && ai->freeResources().canAfford(VLC->creh->creatures[type]->cost))
  709. dwellings.push_back(d);
  710. }
  711. }
  712. }
  713. }
  714. if (dwellings.size())
  715. {
  716. boost::sort(dwellings, isCloser);
  717. return sptr (Goals::GetObj(dwellings.front()->id.getNum()));
  718. }
  719. else
  720. return sptr (Goals::Explore());
  721. //TODO: exchange troops between heroes
  722. }
  723. TSubgoal Conquer::whatToDoToAchieve()
  724. {
  725. return fh->chooseSolution (getAllPossibleSubgoals());
  726. }
  727. TGoalVec Conquer::getAllPossibleSubgoals()
  728. {
  729. TGoalVec ret;
  730. auto conquerable = [](const CGObjectInstance * obj) -> bool
  731. {
  732. if (cb->getPlayerRelations(ai->playerID, obj->tempOwner) == PlayerRelations::ENEMIES)
  733. {
  734. switch (obj->ID.num)
  735. {
  736. case Obj::TOWN:
  737. case Obj::HERO:
  738. case Obj::CREATURE_GENERATOR1:
  739. case Obj::MINE: //TODO: check ai->knownSubterraneanGates
  740. return true;
  741. }
  742. }
  743. return false;
  744. };
  745. std::vector<const CGObjectInstance *> objs;
  746. for (auto obj : ai->visitableObjs)
  747. {
  748. if (conquerable(obj))
  749. objs.push_back (obj);
  750. }
  751. for (auto h : cb->getHeroesInfo())
  752. {
  753. SectorMap sm(h);
  754. std::vector<const CGObjectInstance *> ourObjs(objs); //copy common objects
  755. for (auto obj : ai->reservedHeroesMap[h]) //add objects reserved by this hero
  756. {
  757. if (conquerable(obj))
  758. ourObjs.push_back(obj);
  759. }
  760. for (auto obj : ourObjs) //double loop, performance risk?
  761. {
  762. auto t = sm.firstTileToGet(h, obj->visitablePos()); //we assume that no more than one tile on the way is guarded
  763. ai->whatToDoToReachTile (h, t, ret);
  764. }
  765. }
  766. if (!objs.empty() && ai->canRecruitAnyHero()) //probably no point to recruit hero if we see no objects to capture
  767. ret.push_back (sptr(Goals::RecruitHero()));
  768. if (ret.empty())
  769. ret.push_back (sptr(Goals::Explore())); //we need to find an enemy
  770. return ret;
  771. }
  772. TSubgoal Build::whatToDoToAchieve()
  773. {
  774. return iAmElementar();
  775. }
  776. TSubgoal Invalid::whatToDoToAchieve()
  777. {
  778. return iAmElementar();
  779. }
  780. std::string GatherArmy::completeMessage() const
  781. {
  782. return "Hero " + hero.get()->name + " gathered army of value " + boost::lexical_cast<std::string>(value);
  783. }
  784. TSubgoal GatherArmy::whatToDoToAchieve()
  785. {
  786. //TODO: find hero if none set
  787. assert(hero.h);
  788. return fh->chooseSolution (getAllPossibleSubgoals()); //find dwelling. use current hero to prevent him from doing nothing.
  789. }
  790. TGoalVec GatherArmy::getAllPossibleSubgoals()
  791. {
  792. //get all possible towns, heroes and dwellings we may use
  793. TGoalVec ret;
  794. //TODO: include evaluation of monsters gather in calculation
  795. for (auto t : cb->getTownsInfo())
  796. {
  797. auto pos = t->visitablePos();
  798. if (ai->isAccessibleForHero(pos, hero))
  799. {
  800. if(!t->visitingHero && howManyReinforcementsCanGet(hero,t))
  801. {
  802. if (!vstd::contains (ai->townVisitsThisWeek[hero], t))
  803. ret.push_back (sptr (Goals::VisitTile(pos).sethero(hero)));
  804. }
  805. auto bid = ai->canBuildAnyStructure(t, std::vector<BuildingID>
  806. (unitsSource, unitsSource + ARRAY_COUNT(unitsSource)), 8 - cb->getDate(Date::DAY_OF_WEEK));
  807. if (bid != BuildingID::NONE)
  808. ret.push_back (sptr(BuildThis(bid, t)));
  809. }
  810. }
  811. auto otherHeroes = cb->getHeroesInfo();
  812. auto heroDummy = hero;
  813. erase_if(otherHeroes, [heroDummy](const CGHeroInstance * h)
  814. {
  815. return (h == heroDummy.h || !ai->isAccessibleForHero(heroDummy->visitablePos(), h, true)
  816. || !ai->canGetArmy(heroDummy.h, h) || ai->getGoal(h)->goalType == Goals::GATHER_ARMY);
  817. });
  818. for (auto h : otherHeroes)
  819. {
  820. ret.push_back (sptr (Goals::VisitHero(h->id.getNum()).setisAbstract(true).sethero(hero)));
  821. //go to the other hero if we are faster
  822. ret.push_back (sptr (Goals::VisitHero(hero->id.getNum()).setisAbstract(true).sethero(h)));
  823. //let the other hero come to us
  824. }
  825. std::vector <const CGObjectInstance *> objs;
  826. for (auto obj : ai->visitableObjs)
  827. {
  828. if(obj->ID == Obj::CREATURE_GENERATOR1)
  829. {
  830. auto relationToOwner = cb->getPlayerRelations(obj->getOwner(), ai->playerID);
  831. //Use flagged dwellings only when there are available creatures that we can afford
  832. if(relationToOwner == PlayerRelations::SAME_PLAYER)
  833. {
  834. auto dwelling = dynamic_cast<const CGDwelling*>(obj);
  835. for(auto & creLevel : dwelling->creatures)
  836. {
  837. if(creLevel.first)
  838. {
  839. for(auto & creatureID : creLevel.second)
  840. {
  841. auto creature = VLC->creh->creatures[creatureID];
  842. if (ai->freeResources().canAfford(creature->cost))
  843. objs.push_back(obj);
  844. }
  845. }
  846. }
  847. }
  848. }
  849. }
  850. for(auto h : cb->getHeroesInfo())
  851. {
  852. for (auto obj : objs)
  853. { //find safe dwelling
  854. auto pos = obj->visitablePos();
  855. if (ai->isGoodForVisit(obj, h))
  856. ret.push_back (sptr (Goals::VisitTile(pos).sethero(h)));
  857. }
  858. }
  859. if (ai->canRecruitAnyHero()) //this is not stupid in early phase of game
  860. ret.push_back (sptr(Goals::RecruitHero()));
  861. if (ret.empty())
  862. {
  863. if (hero == ai->primaryHero() || value >= 1.1f)
  864. ret.push_back (sptr(Goals::Explore()));
  865. else //workaround to break loop - seemingly there are no ways to explore left
  866. throw goalFulfilledException (sptr(Goals::GatherArmy(0).sethero(hero)));
  867. }
  868. return ret;
  869. }
  870. //TSubgoal AbstractGoal::whatToDoToAchieve()
  871. //{
  872. // logAi->debugStream() << boost::format("Decomposing goal of type %s") % name();
  873. // return sptr (Goals::Explore());
  874. //}
  875. TSubgoal AbstractGoal::goVisitOrLookFor(const CGObjectInstance *obj)
  876. {
  877. if(obj)
  878. return sptr (Goals::GetObj(obj->id.getNum()));
  879. else
  880. return sptr (Goals::Explore());
  881. }
  882. TSubgoal AbstractGoal::lookForArtSmart(int aid)
  883. {
  884. return sptr (Goals::Invalid());
  885. }
  886. bool AbstractGoal::invalid() const
  887. {
  888. return goalType == INVALID;
  889. }
  890. void AbstractGoal::accept (VCAI * ai)
  891. {
  892. ai->tryRealize(*this);
  893. }
  894. template<typename T>
  895. void CGoal<T>::accept (VCAI * ai)
  896. {
  897. ai->tryRealize(static_cast<T&>(*this)); //casting enforces template instantiation
  898. }
  899. float AbstractGoal::accept (FuzzyHelper * f)
  900. {
  901. return f->evaluate(*this);
  902. }
  903. template<typename T>
  904. float CGoal<T>::accept (FuzzyHelper * f)
  905. {
  906. return f->evaluate(static_cast<T&>(*this)); //casting enforces template instantiation
  907. }