Goals.cpp 31 KB

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