Goals.cpp 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618
  1. /*
  2. * Goals.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "Goals.h"
  12. #include "VCAI.h"
  13. #include "FuzzyHelper.h"
  14. #include "ResourceManager.h"
  15. #include "BuildingManager.h"
  16. #include "../../lib/mapping/CMap.h" //for victory conditions
  17. #include "../../lib/CPathfinder.h"
  18. #include "../../lib/StringConstants.h"
  19. #include "AIhelper.h"
  20. extern boost::thread_specific_ptr<CCallback> cb;
  21. extern boost::thread_specific_ptr<VCAI> ai;
  22. extern FuzzyHelper * fh;
  23. using namespace Goals;
  24. TSubgoal Goals::sptr(const AbstractGoal & tmp)
  25. {
  26. TSubgoal ptr;
  27. ptr.reset(tmp.clone());
  28. return ptr;
  29. }
  30. std::string Goals::AbstractGoal::name() const //TODO: virtualize
  31. {
  32. std::string desc;
  33. switch(goalType)
  34. {
  35. case INVALID:
  36. return "INVALID";
  37. case WIN:
  38. return "WIN";
  39. case DO_NOT_LOSE:
  40. return "DO NOT LOOSE";
  41. case CONQUER:
  42. return "CONQUER";
  43. case BUILD:
  44. return "BUILD";
  45. case EXPLORE:
  46. desc = "EXPLORE";
  47. break;
  48. case GATHER_ARMY:
  49. desc = "GATHER ARMY";
  50. break;
  51. case BUY_ARMY:
  52. return "BUY ARMY";
  53. break;
  54. case BOOST_HERO:
  55. desc = "BOOST_HERO (unsupported)";
  56. break;
  57. case RECRUIT_HERO:
  58. return "RECRUIT HERO";
  59. case BUILD_STRUCTURE:
  60. return "BUILD STRUCTURE";
  61. case COLLECT_RES:
  62. desc = "COLLECT RESOURCE " + GameConstants::RESOURCE_NAMES[resID] + " (" + boost::lexical_cast<std::string>(value) + ")";
  63. break;
  64. case TRADE:
  65. {
  66. auto obj = cb->getObjInstance(ObjectInstanceID(objid));
  67. if (obj)
  68. desc = (boost::format("TRADE %d of %s at %s") % value % GameConstants::RESOURCE_NAMES[resID] % obj->getObjectName()).str();
  69. }
  70. break;
  71. case GATHER_TROOPS:
  72. desc = "GATHER TROOPS";
  73. break;
  74. case VISIT_OBJ:
  75. {
  76. auto obj = cb->getObjInstance(ObjectInstanceID(objid));
  77. if(obj)
  78. desc = "GET OBJ " + obj->getObjectName();
  79. }
  80. break;
  81. case FIND_OBJ:
  82. desc = "FIND OBJ " + boost::lexical_cast<std::string>(objid);
  83. break;
  84. case VISIT_HERO:
  85. {
  86. auto obj = cb->getObjInstance(ObjectInstanceID(objid));
  87. if(obj)
  88. desc = "VISIT HERO " + obj->getObjectName();
  89. }
  90. break;
  91. case GET_ART_TYPE:
  92. desc = "GET ARTIFACT OF TYPE " + VLC->arth->artifacts[aid]->Name();
  93. break;
  94. case ISSUE_COMMAND:
  95. return "ISSUE COMMAND (unsupported)";
  96. case VISIT_TILE:
  97. desc = "VISIT TILE " + tile.toString();
  98. break;
  99. case CLEAR_WAY_TO:
  100. desc = "CLEAR WAY TO " + tile.toString();
  101. break;
  102. case DIG_AT_TILE:
  103. desc = "DIG AT TILE " + tile.toString();
  104. break;
  105. default:
  106. return boost::lexical_cast<std::string>(goalType);
  107. }
  108. if(hero.get(true)) //FIXME: used to crash when we lost hero and failed goal
  109. desc += " (" + hero->name + ")";
  110. return desc;
  111. }
  112. bool Goals::BuildBoat::operator==(const BuildBoat & other) const
  113. {
  114. return shipyard->o->id == other.shipyard->o->id;
  115. }
  116. bool Goals::Explore::operator==(const Explore & other) const
  117. {
  118. return other.hero.h == hero.h;
  119. }
  120. bool Goals::Conquer::operator==(const Conquer & other) const
  121. {
  122. return other.hero.h == hero.h;
  123. }
  124. bool Goals::GatherArmy::operator==(const GatherArmy & other) const
  125. {
  126. return other.hero.h == hero.h || town == other.town;
  127. }
  128. bool Goals::BuyArmy::operator==(const BuyArmy & other) const
  129. {
  130. return town == other.town;
  131. }
  132. bool Goals::BoostHero::operator==(const BoostHero & other) const
  133. {
  134. return other.hero.h == hero.h;
  135. }
  136. bool Goals::BuildThis::operator==(const BuildThis & other) const
  137. {
  138. return town == other.town && bid == other.bid;
  139. }
  140. bool Goals::CollectRes::operator==(const CollectRes & other) const
  141. {
  142. return resID == other.resID;
  143. }
  144. bool Goals::Trade::operator==(const Trade & other) const
  145. {
  146. return resID == other.resID;
  147. }
  148. bool Goals::GatherTroops::operator==(const GatherTroops & other) const
  149. {
  150. return objid == other.objid;
  151. }
  152. bool Goals::VisitObj::operator==(const VisitObj & other) const
  153. {
  154. return other.hero.h == hero.h && other.objid == objid;
  155. }
  156. bool Goals::FindObj::operator==(const FindObj & other) const
  157. {
  158. return other.hero.h == hero.h && other.objid == objid;
  159. }
  160. bool Goals::VisitHero::operator==(const VisitHero & other) const
  161. {
  162. return other.hero.h == hero.h && other.objid == objid;
  163. }
  164. bool Goals::GetArtOfType::operator==(const GetArtOfType & other) const
  165. {
  166. return other.hero.h == hero.h && other.objid == objid;
  167. }
  168. bool Goals::VisitTile::operator==(const VisitTile & other) const
  169. {
  170. return other.hero.h == hero.h && other.tile == tile;
  171. }
  172. bool Goals::ClearWayTo::operator==(const ClearWayTo & other) const
  173. {
  174. return other.hero.h == hero.h && other.tile == tile;
  175. }
  176. bool Goals::DigAtTile::operator==(const DigAtTile & other) const
  177. {
  178. return other.hero.h == hero.h && other.tile == tile;
  179. }
  180. bool Goals::AbstractGoal::operator==(const AbstractGoal & g) const
  181. {
  182. return false;
  183. }
  184. bool Goals::AbstractGoal::operator<(AbstractGoal & g) //for std::unique
  185. {
  186. //TODO: make sure it gets goals consistent with == operator
  187. if (goalType < g.goalType)
  188. return true;
  189. if (goalType > g.goalType)
  190. return false;
  191. if (hero < g.hero)
  192. return true;
  193. if (hero > g.hero)
  194. return false;
  195. if (tile < g.tile)
  196. return true;
  197. if (g.tile < tile)
  198. return false;
  199. if (objid < g.objid)
  200. return true;
  201. if (objid > g.objid)
  202. return false;
  203. if (town < g.town)
  204. return true;
  205. if (town > g.town)
  206. return false;
  207. if (value < g.value)
  208. return true;
  209. if (value > g.value)
  210. return false;
  211. if (priority < g.priority)
  212. return true;
  213. if (priority > g.priority)
  214. return false;
  215. if (resID < g.resID)
  216. return true;
  217. if (resID > g.resID)
  218. return false;
  219. if (bid < g.bid)
  220. return true;
  221. if (bid > g.bid)
  222. return false;
  223. if (aid < g.aid)
  224. return true;
  225. if (aid > g.aid)
  226. return false;
  227. return false;
  228. }
  229. //TODO: find out why the following are not generated automatically on MVS?
  230. namespace Goals
  231. {
  232. template<>
  233. void CGoal<Win>::accept(VCAI * ai)
  234. {
  235. ai->tryRealize(static_cast<Win &>(*this));
  236. }
  237. template<>
  238. void CGoal<Build>::accept(VCAI * ai)
  239. {
  240. ai->tryRealize(static_cast<Build &>(*this));
  241. }
  242. template<>
  243. float CGoal<Win>::accept(FuzzyHelper * f)
  244. {
  245. return f->evaluate(static_cast<Win &>(*this));
  246. }
  247. template<>
  248. float CGoal<Build>::accept(FuzzyHelper * f)
  249. {
  250. return f->evaluate(static_cast<Build &>(*this));
  251. }
  252. bool TSubgoal::operator==(const TSubgoal & rhs) const
  253. {
  254. return *get() == *rhs.get(); //comparison for Goals is overloaded, so they don't need to be identical to match
  255. }
  256. bool TSubgoal::operator<(const TSubgoal & rhs) const
  257. {
  258. return get() < rhs.get(); //compae by value
  259. }
  260. bool BuyArmy::fulfillsMe(TSubgoal goal)
  261. {
  262. //if (hero && hero != goal->hero)
  263. // return false;
  264. return town == goal->town && goal->value >= value; //can always buy more army
  265. }
  266. TSubgoal BuyArmy::whatToDoToAchieve()
  267. {
  268. //TODO: calculate the actual cost of units instead
  269. TResources price;
  270. price[Res::GOLD] = value * 0.4f; //some approximate value
  271. return ai->ah->whatToDo(price, iAmElementar()); //buy right now or gather resources
  272. }
  273. std::string BuyArmy::completeMessage() const
  274. {
  275. return boost::format("Bought army of value %d in town of %s") % value, town->name;
  276. }
  277. }
  278. TSubgoal Trade::whatToDoToAchieve()
  279. {
  280. return iAmElementar();
  281. }
  282. //TSubgoal AbstractGoal::whatToDoToAchieve()
  283. //{
  284. // logAi->debug("Decomposing goal of type %s",name());
  285. // return sptr (Goals::Explore());
  286. //}
  287. TSubgoal Win::whatToDoToAchieve()
  288. {
  289. auto toBool = [=](const EventCondition &)
  290. {
  291. // TODO: proper implementation
  292. // Right now even already fulfilled goals will be included into generated list
  293. // Proper check should test if event condition is already fulfilled
  294. // Easiest way to do this is to call CGameState::checkForVictory but this function should not be
  295. // used on client side or in AI code
  296. return false;
  297. };
  298. std::vector<EventCondition> goals;
  299. for(const TriggeredEvent & event : cb->getMapHeader()->triggeredEvents)
  300. {
  301. //TODO: try to eliminate human player(s) using loss conditions that have isHuman element
  302. if(event.effect.type == EventEffect::VICTORY)
  303. {
  304. boost::range::copy(event.trigger.getFulfillmentCandidates(toBool), std::back_inserter(goals));
  305. }
  306. }
  307. //TODO: instead of returning first encountered goal AI should generate list of possible subgoals
  308. for(const EventCondition & goal : goals)
  309. {
  310. switch(goal.condition)
  311. {
  312. case EventCondition::HAVE_ARTIFACT:
  313. return sptr(Goals::GetArtOfType(goal.objectType));
  314. case EventCondition::DESTROY:
  315. {
  316. if(goal.object)
  317. {
  318. auto obj = cb->getObj(goal.object->id);
  319. if(obj)
  320. if(obj->getOwner() == ai->playerID) //we can't capture our own object
  321. return sptr(Goals::Conquer());
  322. return sptr(Goals::VisitObj(goal.object->id.getNum()));
  323. }
  324. else
  325. {
  326. // TODO: destroy all objects of type goal.objectType
  327. // This situation represents "kill all creatures" condition from H3
  328. break;
  329. }
  330. }
  331. case EventCondition::HAVE_BUILDING:
  332. {
  333. // TODO build other buildings apart from Grail
  334. // goal.objectType = buidingID to build
  335. // goal.object = optional, town in which building should be built
  336. // Represents "Improve town" condition from H3 (but unlike H3 it consists from 2 separate conditions)
  337. if(goal.objectType == BuildingID::GRAIL)
  338. {
  339. if(auto h = ai->getHeroWithGrail())
  340. {
  341. //hero is in a town that can host Grail
  342. if(h->visitedTown && !vstd::contains(h->visitedTown->forbiddenBuildings, BuildingID::GRAIL))
  343. {
  344. const CGTownInstance * t = h->visitedTown;
  345. return sptr(Goals::BuildThis(BuildingID::GRAIL, t).setpriority(10));
  346. }
  347. else
  348. {
  349. auto towns = cb->getTownsInfo();
  350. towns.erase(boost::remove_if(towns,
  351. [](const CGTownInstance * t) -> bool
  352. {
  353. return vstd::contains(t->forbiddenBuildings, BuildingID::GRAIL);
  354. }),
  355. towns.end());
  356. boost::sort(towns, CDistanceSorter(h.get()));
  357. if(towns.size())
  358. {
  359. return sptr(Goals::VisitTile(towns.front()->visitablePos()).sethero(h));
  360. }
  361. }
  362. }
  363. double ratio = 0;
  364. // maybe make this check a bit more complex? For example:
  365. // 0.75 -> dig randomly within 3 tiles radius
  366. // 0.85 -> radius now 2 tiles
  367. // 0.95 -> 1 tile radius, position is fully known
  368. // AFAIK H3 AI does something like this
  369. int3 grailPos = cb->getGrailPos(&ratio);
  370. if(ratio > 0.99)
  371. {
  372. return sptr(Goals::DigAtTile(grailPos));
  373. } //TODO: use FIND_OBJ
  374. else if(const CGObjectInstance * obj = ai->getUnvisitedObj(objWithID<Obj::OBELISK>)) //there are unvisited Obelisks
  375. return sptr(Goals::VisitObj(obj->id.getNum()));
  376. else
  377. return sptr(Goals::Explore());
  378. }
  379. break;
  380. }
  381. case EventCondition::CONTROL:
  382. {
  383. if(goal.object)
  384. {
  385. return sptr(Goals::VisitObj(goal.object->id.getNum()));
  386. }
  387. else
  388. {
  389. //TODO: control all objects of type "goal.objectType"
  390. // Represents H3 condition "Flag all mines"
  391. break;
  392. }
  393. }
  394. case EventCondition::HAVE_RESOURCES:
  395. //TODO mines? piles? marketplace?
  396. //save?
  397. return sptr(Goals::CollectRes(static_cast<Res::ERes>(goal.objectType), goal.value));
  398. case EventCondition::HAVE_CREATURES:
  399. return sptr(Goals::GatherTroops(goal.objectType, goal.value));
  400. case EventCondition::TRANSPORT:
  401. {
  402. //TODO. merge with bring Grail to town? So AI will first dig grail, then transport it using this goal and builds it
  403. // Represents "transport artifact" condition:
  404. // goal.objectType = type of artifact
  405. // goal.object = destination-town where artifact should be transported
  406. break;
  407. }
  408. case EventCondition::STANDARD_WIN:
  409. return sptr(Goals::Conquer());
  410. // Conditions that likely don't need any implementation
  411. case EventCondition::DAYS_PASSED:
  412. break; // goal.value = number of days for condition to trigger
  413. case EventCondition::DAYS_WITHOUT_TOWN:
  414. break; // goal.value = number of days to trigger this
  415. case EventCondition::IS_HUMAN:
  416. break; // Should be only used in calculation of candidates (see toBool lambda)
  417. case EventCondition::CONST_VALUE:
  418. break;
  419. case EventCondition::HAVE_0:
  420. case EventCondition::HAVE_BUILDING_0:
  421. case EventCondition::DESTROY_0:
  422. //TODO: support new condition format
  423. return sptr(Goals::Conquer());
  424. default:
  425. assert(0);
  426. }
  427. }
  428. return sptr(Goals::Invalid());
  429. }
  430. TSubgoal BuildBoat::whatToDoToAchieve()
  431. {
  432. if(cb->getPlayerRelations(ai->playerID, shipyard->o->tempOwner) == PlayerRelations::ENEMIES)
  433. {
  434. return fh->chooseSolution(ai->ah->howToVisitObj(shipyard->o));
  435. }
  436. if(shipyard->shipyardStatus() != IShipyard::GOOD)
  437. {
  438. throw cannotFulfillGoalException("Shipyard is busy.");
  439. }
  440. TResources boatCost;
  441. shipyard->getBoatCost(boatCost);
  442. return ai->ah->whatToDo(boatCost, this->iAmElementar());
  443. }
  444. void BuildBoat::accept(VCAI * ai)
  445. {
  446. TResources boatCost;
  447. shipyard->getBoatCost(boatCost);
  448. if(!cb->getResourceAmount().canAfford(boatCost))
  449. {
  450. throw cannotFulfillGoalException("Can not afford boat");
  451. }
  452. if(cb->getPlayerRelations(ai->playerID, shipyard->o->tempOwner) == PlayerRelations::ENEMIES)
  453. {
  454. throw cannotFulfillGoalException("Can not build boat in enemy shipyard");
  455. }
  456. if(shipyard->shipyardStatus() != IShipyard::GOOD)
  457. {
  458. throw cannotFulfillGoalException("Shipyard is busy.");
  459. }
  460. cb->buildBoat(shipyard);
  461. }
  462. std::string BuildBoat::name() const
  463. {
  464. return "BuildBoat";
  465. }
  466. std::string BuildBoat::completeMessage() const
  467. {
  468. return "Boat have been built at " + shipyard->o->visitablePos().toString();
  469. }
  470. TSubgoal FindObj::whatToDoToAchieve()
  471. {
  472. const CGObjectInstance * o = nullptr;
  473. if(resID > -1) //specified
  474. {
  475. for(const CGObjectInstance * obj : ai->visitableObjs)
  476. {
  477. if(obj->ID == objid && obj->subID == resID)
  478. {
  479. o = obj;
  480. break; //TODO: consider multiple objects and choose best
  481. }
  482. }
  483. }
  484. else
  485. {
  486. for(const CGObjectInstance * obj : ai->visitableObjs)
  487. {
  488. if(obj->ID == objid)
  489. {
  490. o = obj;
  491. break; //TODO: consider multiple objects and choose best
  492. }
  493. }
  494. }
  495. if(o && ai->isAccessible(o->pos)) //we don't use isAccessibleForHero as we don't know which hero it is
  496. return sptr(Goals::VisitObj(o->id.getNum()));
  497. else
  498. return sptr(Goals::Explore());
  499. }
  500. bool Goals::FindObj::fulfillsMe(TSubgoal goal)
  501. {
  502. if (goal->goalType == Goals::VISIT_TILE) //visiting tile visits object at same time
  503. {
  504. if (!hero || hero == goal->hero)
  505. for (auto obj : cb->getVisitableObjs(goal->tile)) //check if any object on that tile matches criteria
  506. if (obj->visitablePos() == goal->tile) //object could be removed
  507. if (obj->ID == objid && obj->subID == resID) //same type and subtype
  508. return true;
  509. }
  510. return false;
  511. }
  512. std::string VisitObj::completeMessage() const
  513. {
  514. return "hero " + hero.get()->name + " captured Object ID = " + boost::lexical_cast<std::string>(objid);
  515. }
  516. TGoalVec VisitObj::getAllPossibleSubgoals()
  517. {
  518. TGoalVec goalList;
  519. const CGObjectInstance * obj = cb->getObjInstance(ObjectInstanceID(objid));
  520. if(!obj)
  521. {
  522. throw cannotFulfillGoalException("Object is missing - goal is invalid now!");
  523. }
  524. int3 pos = obj->visitablePos();
  525. if(hero)
  526. {
  527. if(ai->isAccessibleForHero(pos, hero))
  528. {
  529. if(isSafeToVisit(hero, pos))
  530. goalList.push_back(sptr(Goals::VisitObj(obj->id.getNum()).sethero(hero)));
  531. else
  532. goalList.push_back(sptr(Goals::GatherArmy(evaluateDanger(pos, hero.h) * SAFE_ATTACK_CONSTANT).sethero(hero).setisAbstract(true)));
  533. return goalList;
  534. }
  535. }
  536. else
  537. {
  538. for(auto potentialVisitor : cb->getHeroesInfo())
  539. {
  540. if(ai->isAccessibleForHero(pos, potentialVisitor))
  541. {
  542. if(isSafeToVisit(potentialVisitor, pos))
  543. goalList.push_back(sptr(Goals::VisitObj(obj->id.getNum()).sethero(potentialVisitor)));
  544. else
  545. goalList.push_back(sptr(Goals::GatherArmy(evaluateDanger(pos, potentialVisitor) * SAFE_ATTACK_CONSTANT).sethero(potentialVisitor).setisAbstract(true)));
  546. }
  547. }
  548. if(!goalList.empty())
  549. {
  550. return goalList;
  551. }
  552. }
  553. goalList.push_back(sptr(Goals::ClearWayTo(pos)));
  554. return goalList;
  555. }
  556. TSubgoal VisitObj::whatToDoToAchieve()
  557. {
  558. auto bestGoal = fh->chooseSolution(getAllPossibleSubgoals());
  559. if(bestGoal->goalType == Goals::VISIT_OBJ && bestGoal->hero)
  560. bestGoal->setisElementar(true);
  561. return bestGoal;
  562. }
  563. Goals::VisitObj::VisitObj(int Objid) : CGoal(Goals::VISIT_OBJ)
  564. {
  565. objid = Objid;
  566. tile = ai->myCb->getObjInstance(ObjectInstanceID(objid))->visitablePos();
  567. priority = 3;
  568. }
  569. bool VisitObj::fulfillsMe(TSubgoal goal)
  570. {
  571. if(goal->goalType == Goals::VISIT_TILE)
  572. {
  573. if (!hero || hero == goal->hero)
  574. {
  575. auto obj = cb->getObjInstance(ObjectInstanceID(objid));
  576. if (obj && obj->visitablePos() == goal->tile) //object could be removed
  577. return true;
  578. }
  579. }
  580. return false;
  581. }
  582. std::string VisitHero::completeMessage() const
  583. {
  584. return "hero " + hero.get()->name + " visited hero " + boost::lexical_cast<std::string>(objid);
  585. }
  586. TSubgoal VisitHero::whatToDoToAchieve()
  587. {
  588. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(objid));
  589. if(!obj)
  590. return sptr(Goals::Explore());
  591. int3 pos = obj->visitablePos();
  592. if(hero && ai->isAccessibleForHero(pos, hero, true) && isSafeToVisit(hero, pos)) //enemy heroes can get reinforcements
  593. {
  594. if(hero->pos == pos)
  595. logAi->error("Hero %s tries to visit himself.", hero.name);
  596. else
  597. {
  598. //can't use VISIT_TILE here as tile appears blocked by target hero
  599. //FIXME: elementar goal should not be abstract
  600. return sptr(Goals::VisitHero(objid).sethero(hero).settile(pos).setisElementar(true));
  601. }
  602. }
  603. return sptr(Goals::Invalid());
  604. }
  605. bool VisitHero::fulfillsMe(TSubgoal goal)
  606. {
  607. //TODO: VisitObj shoudl not be used for heroes, but...
  608. if(goal->goalType == Goals::VISIT_TILE)
  609. {
  610. auto obj = cb->getObj(ObjectInstanceID(objid));
  611. if (!obj)
  612. {
  613. logAi->error("Hero %s: VisitHero::fulfillsMe at %s: object %d not found", hero.name, goal->tile.toString(), objid);
  614. return false;
  615. }
  616. return obj->visitablePos() == goal->tile;
  617. }
  618. return false;
  619. }
  620. TSubgoal GetArtOfType::whatToDoToAchieve()
  621. {
  622. TSubgoal alternativeWay = CGoal::lookForArtSmart(aid); //TODO: use
  623. if(alternativeWay->invalid())
  624. return sptr(Goals::FindObj(Obj::ARTIFACT, aid));
  625. return sptr(Goals::Invalid());
  626. }
  627. TSubgoal ClearWayTo::whatToDoToAchieve()
  628. {
  629. assert(cb->isInTheMap(tile)); //set tile
  630. if(!cb->isVisible(tile))
  631. {
  632. logAi->error("Clear way should be used with visible tiles!");
  633. return sptr(Goals::Explore());
  634. }
  635. return (fh->chooseSolution(getAllPossibleSubgoals()));
  636. }
  637. bool Goals::ClearWayTo::fulfillsMe(TSubgoal goal)
  638. {
  639. if (goal->goalType == Goals::VISIT_TILE)
  640. {
  641. if (!hero || hero == goal->hero)
  642. return tile == goal->tile;
  643. }
  644. return false;
  645. }
  646. TGoalVec ClearWayTo::getAllPossibleSubgoals()
  647. {
  648. TGoalVec ret;
  649. std::vector<const CGHeroInstance *> heroes;
  650. if(hero)
  651. heroes.push_back(hero.h);
  652. else
  653. heroes = cb->getHeroesInfo();
  654. for(auto h : heroes)
  655. {
  656. //TODO: handle clearing way to allied heroes that are blocked
  657. //if ((hero && hero->visitablePos() == tile && hero == *h) || //we can't free the way ourselves
  658. // h->visitablePos() == tile) //we are already on that tile! what does it mean?
  659. // continue;
  660. //if our hero is trapped, make sure we request clearing the way from OUR perspective
  661. vstd::concatenate(ret, ai->ah->howToVisitTile(h, tile));
  662. }
  663. if(ret.empty() && ai->canRecruitAnyHero())
  664. ret.push_back(sptr(Goals::RecruitHero()));
  665. if(ret.empty())
  666. {
  667. logAi->warn("There is no known way to clear the way to tile %s", tile.toString());
  668. throw goalFulfilledException(sptr(Goals::ClearWayTo(tile))); //make sure asigned hero gets unlocked
  669. }
  670. return ret;
  671. }
  672. std::string Explore::completeMessage() const
  673. {
  674. return "Hero " + hero.get()->name + " completed exploration";
  675. }
  676. TSubgoal Explore::whatToDoToAchieve()
  677. {
  678. auto ret = fh->chooseSolution(getAllPossibleSubgoals());
  679. if(hero) //use best step for this hero
  680. {
  681. return ret;
  682. }
  683. else
  684. {
  685. if(ret->hero.get(true))
  686. return sptr(sethero(ret->hero.h).setisAbstract(true)); //choose this hero and then continue with him
  687. else
  688. return ret; //other solutions, like buying hero from tavern
  689. }
  690. }
  691. TGoalVec Explore::getAllPossibleSubgoals()
  692. {
  693. TGoalVec ret;
  694. std::vector<const CGHeroInstance *> heroes;
  695. if(hero)
  696. {
  697. heroes.push_back(hero.h);
  698. }
  699. else
  700. {
  701. //heroes = ai->getUnblockedHeroes();
  702. heroes = cb->getHeroesInfo();
  703. vstd::erase_if(heroes, [](const HeroPtr h)
  704. {
  705. if(ai->getGoal(h)->goalType == Goals::EXPLORE) //do not reassign hero who is already explorer
  706. return true;
  707. if(!ai->isAbleToExplore(h))
  708. return true;
  709. return !h->movement; //saves time, immobile heroes are useless anyway
  710. });
  711. }
  712. //try to use buildings that uncover map
  713. std::vector<const CGObjectInstance *> objs;
  714. for(auto obj : ai->visitableObjs)
  715. {
  716. if(!vstd::contains(ai->alreadyVisited, obj))
  717. {
  718. switch(obj->ID.num)
  719. {
  720. case Obj::REDWOOD_OBSERVATORY:
  721. case Obj::PILLAR_OF_FIRE:
  722. case Obj::CARTOGRAPHER:
  723. objs.push_back(obj);
  724. break;
  725. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  726. case Obj::MONOLITH_TWO_WAY:
  727. case Obj::SUBTERRANEAN_GATE:
  728. auto tObj = dynamic_cast<const CGTeleport *>(obj);
  729. assert(ai->knownTeleportChannels.find(tObj->channel) != ai->knownTeleportChannels.end());
  730. if(TeleportChannel::IMPASSABLE != ai->knownTeleportChannels[tObj->channel]->passability)
  731. objs.push_back(obj);
  732. break;
  733. }
  734. }
  735. else
  736. {
  737. switch(obj->ID.num)
  738. {
  739. case Obj::MONOLITH_TWO_WAY:
  740. case Obj::SUBTERRANEAN_GATE:
  741. auto tObj = dynamic_cast<const CGTeleport *>(obj);
  742. if(TeleportChannel::IMPASSABLE == ai->knownTeleportChannels[tObj->channel]->passability)
  743. break;
  744. for(auto exit : ai->knownTeleportChannels[tObj->channel]->exits)
  745. {
  746. if(!cb->getObj(exit))
  747. { // Always attempt to visit two-way teleports if one of channel exits is not visible
  748. objs.push_back(obj);
  749. break;
  750. }
  751. }
  752. break;
  753. }
  754. }
  755. }
  756. auto primaryHero = ai->primaryHero().h;
  757. for(auto h : heroes)
  758. {
  759. for(auto obj : objs) //double loop, performance risk?
  760. {
  761. auto waysToVisitObj = ai->ah->howToVisitObj(h, obj);
  762. vstd::concatenate(ret, waysToVisitObj);
  763. }
  764. int3 t = whereToExplore(h);
  765. if(t.valid())
  766. {
  767. ret.push_back(sptr(Goals::VisitTile(t).sethero(h)));
  768. }
  769. else
  770. {
  771. //FIXME: possible issues when gathering army to break
  772. if(hero.h == h || //exporation is assigned to this hero
  773. (!hero && h == primaryHero)) //not assigned to specific hero, let our main hero do the job
  774. {
  775. t = ai->explorationDesperate(h); //check this only ONCE, high cost
  776. if (t.valid()) //don't waste time if we are completely blocked
  777. {
  778. auto waysToVisitTile = ai->ah->howToVisitTile(h, t);
  779. vstd::concatenate(ret, waysToVisitTile);
  780. continue;
  781. }
  782. }
  783. ai->markHeroUnableToExplore(h); //there is no freely accessible tile, do not poll this hero anymore
  784. }
  785. }
  786. //we either don't have hero yet or none of heroes can explore
  787. if((!hero || ret.empty()) && ai->canRecruitAnyHero())
  788. ret.push_back(sptr(Goals::RecruitHero()));
  789. if(ret.empty())
  790. {
  791. throw goalFulfilledException(sptr(Goals::Explore().sethero(hero)));
  792. }
  793. //throw cannotFulfillGoalException("Cannot explore - no possible ways found!");
  794. return ret;
  795. }
  796. bool Explore::fulfillsMe(TSubgoal goal)
  797. {
  798. if(goal->goalType == Goals::EXPLORE)
  799. {
  800. if(goal->hero)
  801. return hero == goal->hero;
  802. else
  803. return true; //cancel ALL exploration
  804. }
  805. return false;
  806. }
  807. TSubgoal RecruitHero::whatToDoToAchieve()
  808. {
  809. const CGTownInstance * t = ai->findTownWithTavern();
  810. if(!t)
  811. return sptr(Goals::BuildThis(BuildingID::TAVERN).setpriority(2));
  812. TResources res;
  813. res[Res::GOLD] = GameConstants::HERO_GOLD_COST;
  814. return ai->ah->whatToDo(res, iAmElementar()); //either buy immediately, or collect res
  815. }
  816. std::string VisitTile::completeMessage() const
  817. {
  818. return "Hero " + hero.get()->name + " visited tile " + tile.toString();
  819. }
  820. TSubgoal VisitTile::whatToDoToAchieve()
  821. {
  822. auto ret = fh->chooseSolution(getAllPossibleSubgoals());
  823. if(ret->hero)
  824. {
  825. if(isSafeToVisit(ret->hero, tile) && ai->isAccessibleForHero(tile, ret->hero))
  826. {
  827. ret->setisElementar(true);
  828. return ret;
  829. }
  830. else
  831. {
  832. return sptr(Goals::GatherArmy(evaluateDanger(tile, *ret->hero) * SAFE_ATTACK_CONSTANT)
  833. .sethero(ret->hero).setisAbstract(true));
  834. }
  835. }
  836. return ret;
  837. }
  838. TGoalVec VisitTile::getAllPossibleSubgoals()
  839. {
  840. assert(cb->isInTheMap(tile));
  841. TGoalVec ret;
  842. if(!cb->isVisible(tile))
  843. ret.push_back(sptr(Goals::Explore())); //what sense does it make?
  844. else
  845. {
  846. std::vector<const CGHeroInstance *> heroes;
  847. if(hero)
  848. heroes.push_back(hero.h); //use assigned hero if any
  849. else
  850. heroes = cb->getHeroesInfo(); //use most convenient hero
  851. for(auto h : heroes)
  852. {
  853. if(ai->isAccessibleForHero(tile, h))
  854. ret.push_back(sptr(Goals::VisitTile(tile).sethero(h)));
  855. }
  856. if(ai->canRecruitAnyHero())
  857. ret.push_back(sptr(Goals::RecruitHero()));
  858. }
  859. if(ret.empty())
  860. {
  861. auto obj = vstd::frontOrNull(cb->getVisitableObjs(tile));
  862. if(obj && obj->ID == Obj::HERO && obj->tempOwner == ai->playerID) //our own hero stands on that tile
  863. {
  864. if(hero.get(true) && hero->id == obj->id) //if it's assigned hero, visit tile. If it's different hero, we can't visit tile now
  865. ret.push_back(sptr(Goals::VisitTile(tile).sethero(dynamic_cast<const CGHeroInstance *>(obj)).setisElementar(true)));
  866. else
  867. throw cannotFulfillGoalException("Tile is already occupied by another hero "); //FIXME: we should give up this tile earlier
  868. }
  869. else
  870. ret.push_back(sptr(Goals::ClearWayTo(tile)));
  871. }
  872. //important - at least one sub-goal must handle case which is impossible to fulfill (unreachable tile)
  873. return ret;
  874. }
  875. TSubgoal DigAtTile::whatToDoToAchieve()
  876. {
  877. const CGObjectInstance * firstObj = vstd::frontOrNull(cb->getVisitableObjs(tile));
  878. if(firstObj && firstObj->ID == Obj::HERO && firstObj->tempOwner == ai->playerID) //we have hero at dest
  879. {
  880. const CGHeroInstance * h = dynamic_cast<const CGHeroInstance *>(firstObj);
  881. sethero(h).setisElementar(true);
  882. return sptr(*this);
  883. }
  884. return sptr(Goals::VisitTile(tile));
  885. }
  886. TSubgoal BuildThis::whatToDoToAchieve()
  887. {
  888. auto b = BuildingID(bid);
  889. // find town if not set
  890. if (!town && hero)
  891. town = hero->visitedTown;
  892. if (!town)
  893. {
  894. for (const CGTownInstance * t : cb->getTownsInfo())
  895. {
  896. switch (cb->canBuildStructure(town, b))
  897. {
  898. case EBuildingState::ALLOWED:
  899. town = t;
  900. break; //TODO: look for prerequisites? this is not our reponsibility
  901. default:
  902. continue;
  903. }
  904. }
  905. }
  906. if (town) //we have specific town to build this
  907. {
  908. switch (cb->canBuildStructure(town, b))
  909. {
  910. case EBuildingState::ALLOWED:
  911. case EBuildingState::NO_RESOURCES:
  912. {
  913. auto res = town->town->buildings.at(BuildingID(bid))->resources;
  914. return ai->ah->whatToDo(res, iAmElementar()); //realize immediately or gather resources
  915. }
  916. break;
  917. default:
  918. throw cannotFulfillGoalException("Not possible to build");
  919. }
  920. }
  921. else
  922. throw cannotFulfillGoalException("Cannot find town to build this");
  923. }
  924. TGoalVec Goals::CollectRes::getAllPossibleSubgoals()
  925. {
  926. TGoalVec ret;
  927. auto givesResource = [this](const CGObjectInstance * obj) -> bool
  928. {
  929. //TODO: move this logic to object side
  930. //TODO: remember mithril exists
  931. //TODO: water objects
  932. //TODO: Creature banks
  933. //return false first from once-visitable, before checking if they were even visited
  934. switch (obj->ID.num)
  935. {
  936. case Obj::TREASURE_CHEST:
  937. return resID == Res::GOLD;
  938. break;
  939. case Obj::RESOURCE:
  940. return obj->subID == resID;
  941. break;
  942. case Obj::MINE:
  943. return (obj->subID == resID &&
  944. (cb->getPlayerRelations(obj->tempOwner, ai->playerID) == PlayerRelations::ENEMIES)); //don't capture our mines
  945. break;
  946. case Obj::CAMPFIRE:
  947. return true; //contains all resources
  948. break;
  949. case Obj::WINDMILL:
  950. switch (resID)
  951. {
  952. case Res::GOLD:
  953. case Res::WOOD:
  954. return false;
  955. }
  956. break;
  957. case Obj::WATER_WHEEL:
  958. if (resID != Res::GOLD)
  959. return false;
  960. break;
  961. case Obj::MYSTICAL_GARDEN:
  962. if ((resID != Res::GOLD) && (resID != Res::GEMS))
  963. return false;
  964. break;
  965. case Obj::LEAN_TO:
  966. case Obj::WAGON:
  967. if (resID != Res::GOLD)
  968. return false;
  969. break;
  970. default:
  971. return false;
  972. break;
  973. }
  974. return !vstd::contains(ai->alreadyVisited, obj); //for weekly / once visitable
  975. };
  976. std::vector<const CGObjectInstance *> objs;
  977. for (auto obj : ai->visitableObjs)
  978. {
  979. if (givesResource(obj))
  980. objs.push_back(obj);
  981. }
  982. for (auto h : cb->getHeroesInfo())
  983. {
  984. std::vector<const CGObjectInstance *> ourObjs(objs); //copy common objects
  985. for (auto obj : ai->reservedHeroesMap[h]) //add objects reserved by this hero
  986. {
  987. if (givesResource(obj))
  988. ourObjs.push_back(obj);
  989. }
  990. for (auto obj : ourObjs)
  991. {
  992. auto waysToGo = ai->ah->howToVisitObj(h, ObjectIdRef(obj));
  993. vstd::concatenate(ret, waysToGo);
  994. }
  995. }
  996. return ret;
  997. }
  998. TSubgoal CollectRes::whatToDoToAchieve()
  999. {
  1000. auto goals = getAllPossibleSubgoals();
  1001. auto trade = whatToDoToTrade();
  1002. if (!trade->invalid())
  1003. goals.push_back(trade);
  1004. if (goals.empty())
  1005. return sptr(Goals::Explore()); //we can always do that
  1006. else
  1007. return fh->chooseSolution(goals); //TODO: evaluate trading
  1008. }
  1009. TSubgoal Goals::CollectRes::whatToDoToTrade()
  1010. {
  1011. std::vector<const IMarket *> markets;
  1012. std::vector<const CGObjectInstance *> visObjs;
  1013. ai->retrieveVisitableObjs(visObjs, true);
  1014. for (const CGObjectInstance * obj : visObjs)
  1015. {
  1016. if (const IMarket * m = IMarket::castFrom(obj, false))
  1017. {
  1018. if (obj->ID == Obj::TOWN && obj->tempOwner == ai->playerID && m->allowsTrade(EMarketMode::RESOURCE_RESOURCE))
  1019. markets.push_back(m);
  1020. else if (obj->ID == Obj::TRADING_POST)
  1021. markets.push_back(m);
  1022. }
  1023. }
  1024. boost::sort(markets, [](const IMarket * m1, const IMarket * m2) -> bool
  1025. {
  1026. return m1->getMarketEfficiency() < m2->getMarketEfficiency();
  1027. });
  1028. markets.erase(boost::remove_if(markets, [](const IMarket * market) -> bool
  1029. {
  1030. if (!(market->o->ID == Obj::TOWN && market->o->tempOwner == ai->playerID))
  1031. {
  1032. if (!ai->isAccessible(market->o->visitablePos()))
  1033. return true;
  1034. }
  1035. return false;
  1036. }), markets.end());
  1037. if (!markets.size())
  1038. {
  1039. for (const CGTownInstance * t : cb->getTownsInfo())
  1040. {
  1041. if (cb->canBuildStructure(t, BuildingID::MARKETPLACE) == EBuildingState::ALLOWED)
  1042. return sptr(Goals::BuildThis(BuildingID::MARKETPLACE, t).setpriority(2));
  1043. }
  1044. }
  1045. else
  1046. {
  1047. const IMarket * m = markets.back();
  1048. //attempt trade at back (best prices)
  1049. int howManyCanWeBuy = 0;
  1050. for (Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
  1051. {
  1052. if (i == resID)
  1053. continue;
  1054. int toGive = -1, toReceive = -1;
  1055. m->getOffer(i, resID, toGive, toReceive, EMarketMode::RESOURCE_RESOURCE);
  1056. assert(toGive > 0 && toReceive > 0);
  1057. howManyCanWeBuy += toReceive * (ai->ah->freeResources()[i] / toGive);
  1058. }
  1059. if (howManyCanWeBuy >= value)
  1060. {
  1061. auto backObj = cb->getTopObj(m->o->visitablePos()); //it'll be a hero if we have one there; otherwise marketplace
  1062. assert(backObj);
  1063. auto objid = m->o->id.getNum();
  1064. if (backObj->tempOwner != ai->playerID) //top object not owned
  1065. {
  1066. return sptr(Goals::VisitObj(objid)); //just go there
  1067. }
  1068. else //either it's our town, or we have hero there
  1069. {
  1070. Goals::Trade trade(resID, value, objid);
  1071. return sptr(trade.setisElementar(true)); //we can do this immediately
  1072. }
  1073. }
  1074. }
  1075. return sptr(Goals::Invalid()); //cannot trade
  1076. }
  1077. bool CollectRes::fulfillsMe(TSubgoal goal)
  1078. {
  1079. if (goal->resID == resID)
  1080. if (goal->value >= value)
  1081. return true;
  1082. return false;
  1083. }
  1084. TSubgoal GatherTroops::whatToDoToAchieve()
  1085. {
  1086. std::vector<const CGDwelling *> dwellings;
  1087. for(const CGTownInstance * t : cb->getTownsInfo())
  1088. {
  1089. auto creature = VLC->creh->creatures[objid];
  1090. if(t->subID == creature->faction) //TODO: how to force AI to build unupgraded creatures? :O
  1091. {
  1092. auto creatures = vstd::tryAt(t->town->creatures, creature->level - 1);
  1093. if(!creatures)
  1094. continue;
  1095. int upgradeNumber = vstd::find_pos(*creatures, creature->idNumber);
  1096. if(upgradeNumber < 0)
  1097. continue;
  1098. BuildingID bid(BuildingID::DWELL_FIRST + creature->level - 1 + upgradeNumber * GameConstants::CREATURES_PER_TOWN);
  1099. if(t->hasBuilt(bid)) //this assumes only creatures with dwellings are assigned to faction
  1100. {
  1101. dwellings.push_back(t);
  1102. }
  1103. else
  1104. {
  1105. return sptr(Goals::BuildThis(bid, t).setpriority(priority));
  1106. }
  1107. }
  1108. }
  1109. for(auto obj : ai->visitableObjs)
  1110. {
  1111. if(obj->ID != Obj::CREATURE_GENERATOR1) //TODO: what with other creature generators?
  1112. continue;
  1113. auto d = dynamic_cast<const CGDwelling *>(obj);
  1114. for(auto creature : d->creatures)
  1115. {
  1116. if(creature.first) //there are more than 0 creatures avaliabe
  1117. {
  1118. for(auto type : creature.second)
  1119. {
  1120. if(type == objid && ai->ah->freeResources().canAfford(VLC->creh->creatures[type]->cost))
  1121. dwellings.push_back(d);
  1122. }
  1123. }
  1124. }
  1125. }
  1126. if(dwellings.size())
  1127. {
  1128. typedef std::map<const CGHeroInstance *, const CGDwelling *> TDwellMap;
  1129. // sorted helper
  1130. auto comparator = [](const TDwellMap::value_type & a, const TDwellMap::value_type & b) -> bool
  1131. {
  1132. const CGPathNode * ln = ai->myCb->getPathsInfo(a.first)->getPathInfo(a.second->visitablePos());
  1133. const CGPathNode * rn = ai->myCb->getPathsInfo(b.first)->getPathInfo(b.second->visitablePos());
  1134. if(ln->turns != rn->turns)
  1135. return ln->turns < rn->turns;
  1136. return (ln->moveRemains > rn->moveRemains);
  1137. };
  1138. // for all owned heroes generate map <hero -> nearest dwelling>
  1139. TDwellMap nearestDwellings;
  1140. for(const CGHeroInstance * hero : cb->getHeroesInfo(true))
  1141. {
  1142. nearestDwellings[hero] = *boost::range::min_element(dwellings, CDistanceSorter(hero));
  1143. }
  1144. if(nearestDwellings.size())
  1145. {
  1146. // find hero who is nearest to a dwelling
  1147. const CGDwelling * nearest = boost::range::min_element(nearestDwellings, comparator)->second;
  1148. if(!nearest)
  1149. throw cannotFulfillGoalException("Cannot find nearest dwelling!");
  1150. return sptr(Goals::VisitObj(nearest->id.getNum()));
  1151. }
  1152. else
  1153. return sptr(Goals::Explore());
  1154. }
  1155. else
  1156. {
  1157. return sptr(Goals::Explore());
  1158. }
  1159. //TODO: exchange troops between heroes
  1160. }
  1161. bool Goals::GatherTroops::fulfillsMe(TSubgoal goal)
  1162. {
  1163. if (!hero || hero == goal->hero) //we got army for desired hero or any hero
  1164. if (goal->objid == objid) //same creature type //TODO: consider upgrades?
  1165. if (goal->value >= value) //notify every time we get resources?
  1166. return true;
  1167. return false;
  1168. }
  1169. TSubgoal Conquer::whatToDoToAchieve()
  1170. {
  1171. return fh->chooseSolution(getAllPossibleSubgoals());
  1172. }
  1173. TGoalVec Conquer::getAllPossibleSubgoals()
  1174. {
  1175. TGoalVec ret;
  1176. auto conquerable = [](const CGObjectInstance * obj) -> bool
  1177. {
  1178. if(cb->getPlayerRelations(ai->playerID, obj->tempOwner) == PlayerRelations::ENEMIES)
  1179. {
  1180. switch(obj->ID.num)
  1181. {
  1182. case Obj::TOWN:
  1183. case Obj::HERO:
  1184. case Obj::CREATURE_GENERATOR1:
  1185. case Obj::MINE: //TODO: check ai->knownSubterraneanGates
  1186. return true;
  1187. }
  1188. }
  1189. return false;
  1190. };
  1191. std::vector<const CGObjectInstance *> objs;
  1192. for(auto obj : ai->visitableObjs)
  1193. {
  1194. if(conquerable(obj))
  1195. objs.push_back(obj);
  1196. }
  1197. for(auto h : cb->getHeroesInfo())
  1198. {
  1199. std::vector<const CGObjectInstance *> ourObjs(objs); //copy common objects
  1200. for(auto obj : ai->reservedHeroesMap[h]) //add objects reserved by this hero
  1201. {
  1202. if(conquerable(obj))
  1203. ourObjs.push_back(obj);
  1204. }
  1205. for(auto obj : ourObjs)
  1206. {
  1207. auto waysToGo = ai->ah->howToVisitObj(h, ObjectIdRef(obj));
  1208. vstd::concatenate(ret, waysToGo);
  1209. }
  1210. }
  1211. if(!objs.empty() && ai->canRecruitAnyHero()) //probably no point to recruit hero if we see no objects to capture
  1212. ret.push_back(sptr(Goals::RecruitHero()));
  1213. if(ret.empty())
  1214. ret.push_back(sptr(Goals::Explore())); //we need to find an enemy
  1215. return ret;
  1216. }
  1217. TGoalVec Goals::Build::getAllPossibleSubgoals()
  1218. {
  1219. TGoalVec ret;
  1220. for (const CGTownInstance * t : cb->getTownsInfo())
  1221. {
  1222. //start fresh with every town
  1223. ai->ah->getBuildingOptions(t);
  1224. auto ib = ai->ah->immediateBuilding();
  1225. if (ib.is_initialized())
  1226. {
  1227. ret.push_back(sptr(Goals::BuildThis(ib.get().bid, t).setpriority(2))); //prioritize buildings we can build quick
  1228. }
  1229. else //try build later
  1230. {
  1231. auto eb = ai->ah->expensiveBuilding();
  1232. if (eb.is_initialized())
  1233. {
  1234. auto pb = eb.get(); //gather resources for any we can't afford
  1235. auto goal = ai->ah->whatToDo(pb.price, sptr(Goals::BuildThis(pb.bid, t).setpriority(0.5)));
  1236. ret.push_back(goal);
  1237. }
  1238. }
  1239. }
  1240. if (ret.empty())
  1241. throw cannotFulfillGoalException("BUILD has been realized as much as possible.");
  1242. else
  1243. return ret;
  1244. }
  1245. TSubgoal Build::whatToDoToAchieve()
  1246. {
  1247. return fh->chooseSolution(getAllPossibleSubgoals());
  1248. }
  1249. bool Goals::Build::fulfillsMe(TSubgoal goal)
  1250. {
  1251. if (goal->goalType == Goals::BUILD || goal->goalType == Goals::BUILD_STRUCTURE)
  1252. return (!town || town == goal->town); //building anything will do, in this town if set
  1253. else
  1254. return false;
  1255. }
  1256. TSubgoal Invalid::whatToDoToAchieve()
  1257. {
  1258. return iAmElementar();
  1259. }
  1260. std::string GatherArmy::completeMessage() const
  1261. {
  1262. return "Hero " + hero.get()->name + " gathered army of value " + boost::lexical_cast<std::string>(value);
  1263. }
  1264. TSubgoal GatherArmy::whatToDoToAchieve()
  1265. {
  1266. //TODO: find hero if none set
  1267. assert(hero.h);
  1268. return fh->chooseSolution(getAllPossibleSubgoals()); //find dwelling. use current hero to prevent him from doing nothing.
  1269. }
  1270. static const BuildingID unitsSource[] = { BuildingID::DWELL_LVL_1, BuildingID::DWELL_LVL_2, BuildingID::DWELL_LVL_3,
  1271. BuildingID::DWELL_LVL_4, BuildingID::DWELL_LVL_5, BuildingID::DWELL_LVL_6, BuildingID::DWELL_LVL_7};
  1272. TGoalVec GatherArmy::getAllPossibleSubgoals()
  1273. {
  1274. //get all possible towns, heroes and dwellings we may use
  1275. TGoalVec ret;
  1276. if(!hero.validAndSet())
  1277. {
  1278. return ret;
  1279. }
  1280. //TODO: include evaluation of monsters gather in calculation
  1281. for(auto t : cb->getTownsInfo())
  1282. {
  1283. auto pos = t->visitablePos();
  1284. if(ai->isAccessibleForHero(pos, hero))
  1285. {
  1286. //grab army from town
  1287. if(!t->visitingHero && howManyReinforcementsCanGet(hero, t))
  1288. {
  1289. if(!vstd::contains(ai->townVisitsThisWeek[hero], t))
  1290. ret.push_back(sptr(Goals::VisitTile(pos).sethero(hero)));
  1291. }
  1292. //buy army in town
  1293. if (!t->visitingHero || t->visitingHero == hero.get(true))
  1294. {
  1295. ui32 val = std::min<ui32>(value, howManyReinforcementsCanBuy(hero, t));
  1296. if (val)
  1297. {
  1298. auto goal = sptr(Goals::BuyArmy(t, val).sethero(hero));
  1299. if(!ai->ah->containsObjective(goal)) //avoid loops caused by reserving same objective twice
  1300. ret.push_back(goal);
  1301. else
  1302. logAi->debug("Can not buy army, because of ai->ah->containsObjective");
  1303. }
  1304. }
  1305. //build dwelling
  1306. //TODO: plan building over multiple turns?
  1307. //auto bid = ah->canBuildAnyStructure(t, std::vector<BuildingID>(unitsSource, unitsSource + ARRAY_COUNT(unitsSource)), 8 - cb->getDate(Date::DAY_OF_WEEK));
  1308. auto bid = ai->ah->canBuildAnyStructure(t, std::vector<BuildingID>(unitsSource, unitsSource + ARRAY_COUNT(unitsSource)), 1);
  1309. if (bid.is_initialized())
  1310. {
  1311. auto goal = sptr(BuildThis(bid.get(), t).setpriority(priority));
  1312. if (!ai->ah->containsObjective(goal)) //avoid loops caused by reserving same objective twice
  1313. ret.push_back(goal);
  1314. else
  1315. logAi->debug("Can not build a structure, because of ai->ah->containsObjective");
  1316. }
  1317. }
  1318. }
  1319. auto otherHeroes = cb->getHeroesInfo();
  1320. auto heroDummy = hero;
  1321. vstd::erase_if(otherHeroes, [heroDummy](const CGHeroInstance * h)
  1322. {
  1323. if(h == heroDummy.h)
  1324. return true;
  1325. else if(!ai->isAccessibleForHero(heroDummy->visitablePos(), h, true))
  1326. return true;
  1327. else if(!ai->canGetArmy(heroDummy.h, h)) //TODO: return actual aiValue
  1328. return true;
  1329. else if(ai->getGoal(h)->goalType == Goals::GATHER_ARMY)
  1330. return true;
  1331. else
  1332. return false;
  1333. });
  1334. for(auto h : otherHeroes)
  1335. {
  1336. // Go to the other hero if we are faster
  1337. if (!vstd::contains(ai->visitedHeroes[hero], h)
  1338. && ai->isAccessibleForHero(h->visitablePos(), hero, true)) //visit only once each turn //FIXME: this is only bug workaround
  1339. ret.push_back(sptr(Goals::VisitHero(h->id.getNum()).setisAbstract(true).sethero(hero)));
  1340. // Let the other hero come to us
  1341. if (!vstd::contains(ai->visitedHeroes[h], hero))
  1342. ret.push_back(sptr(Goals::VisitHero(hero->id.getNum()).setisAbstract(true).sethero(h)));
  1343. }
  1344. std::vector<const CGObjectInstance *> objs;
  1345. for(auto obj : ai->visitableObjs)
  1346. {
  1347. if(obj->ID == Obj::CREATURE_GENERATOR1)
  1348. {
  1349. auto relationToOwner = cb->getPlayerRelations(obj->getOwner(), ai->playerID);
  1350. //Use flagged dwellings only when there are available creatures that we can afford
  1351. if(relationToOwner == PlayerRelations::SAME_PLAYER)
  1352. {
  1353. auto dwelling = dynamic_cast<const CGDwelling *>(obj);
  1354. ui32 val = std::min<ui32>(value, howManyReinforcementsCanBuy(hero, dwelling));
  1355. if(val)
  1356. {
  1357. for(auto & creLevel : dwelling->creatures)
  1358. {
  1359. if(creLevel.first)
  1360. {
  1361. for(auto & creatureID : creLevel.second)
  1362. {
  1363. auto creature = VLC->creh->creatures[creatureID];
  1364. if(ai->ah->freeResources().canAfford(creature->cost))
  1365. objs.push_back(obj); //TODO: reserve resources?
  1366. }
  1367. }
  1368. }
  1369. }
  1370. }
  1371. }
  1372. }
  1373. for(auto h : cb->getHeroesInfo())
  1374. {
  1375. for(auto obj : objs)
  1376. {
  1377. //find safe dwelling
  1378. if(ai->isGoodForVisit(obj, h))
  1379. {
  1380. vstd::concatenate(ret, ai->ah->howToVisitObj(h, obj));
  1381. }
  1382. }
  1383. }
  1384. if(ai->canRecruitAnyHero() && ai->ah->freeGold() > GameConstants::HERO_GOLD_COST) //this is not stupid in early phase of game
  1385. {
  1386. if(auto t = ai->findTownWithTavern())
  1387. {
  1388. for(auto h : cb->getAvailableHeroes(t)) //we assume that all towns have same set of heroes
  1389. {
  1390. if(h && h->getTotalStrength() > 500) //do not buy heroes with single creatures for GatherArmy
  1391. {
  1392. ret.push_back(sptr(Goals::RecruitHero()));
  1393. break;
  1394. }
  1395. }
  1396. }
  1397. }
  1398. if(ret.empty())
  1399. {
  1400. if(hero == ai->primaryHero())
  1401. ret.push_back(sptr(Goals::Explore()));
  1402. else
  1403. throw cannotFulfillGoalException("No ways to gather army");
  1404. }
  1405. return ret;
  1406. }
  1407. //TSubgoal AbstractGoal::whatToDoToAchieve()
  1408. //{
  1409. // logAi->debug("Decomposing goal of type %s",name());
  1410. // return sptr (Goals::Explore());
  1411. //}
  1412. TSubgoal AbstractGoal::goVisitOrLookFor(const CGObjectInstance * obj)
  1413. {
  1414. if(obj)
  1415. return sptr(Goals::VisitObj(obj->id.getNum()));
  1416. else
  1417. return sptr(Goals::Explore());
  1418. }
  1419. TSubgoal AbstractGoal::lookForArtSmart(int aid)
  1420. {
  1421. return sptr(Goals::Invalid());
  1422. }
  1423. bool AbstractGoal::invalid() const
  1424. {
  1425. return goalType == INVALID;
  1426. }
  1427. void AbstractGoal::accept(VCAI * ai)
  1428. {
  1429. ai->tryRealize(*this);
  1430. }
  1431. template<typename T>
  1432. void CGoal<T>::accept(VCAI * ai)
  1433. {
  1434. ai->tryRealize(static_cast<T &>(*this)); //casting enforces template instantiation
  1435. }
  1436. float AbstractGoal::accept(FuzzyHelper * f)
  1437. {
  1438. return f->evaluate(*this);
  1439. }
  1440. template<typename T>
  1441. float CGoal<T>::accept(FuzzyHelper * f)
  1442. {
  1443. return f->evaluate(static_cast<T &>(*this)); //casting enforces template instantiation
  1444. }