Fuzzy.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. /*
  2. * Fuzzy.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 "Fuzzy.h"
  12. #include <limits>
  13. #include "../../lib/mapObjects/MapObjects.h"
  14. #include "../../lib/mapObjects/CommonConstructors.h"
  15. #include "../../lib/CCreatureHandler.h"
  16. #include "../../lib/CPathfinder.h"
  17. #include "../../lib/CGameStateFwd.h"
  18. #include "../../lib/VCMI_Lib.h"
  19. #include "../../CCallback.h"
  20. #include "VCAI.h"
  21. #include "MapObjectsEvaluator.h"
  22. #define MIN_AI_STRENGHT (0.5f) //lower when combat AI gets smarter
  23. #define UNGUARDED_OBJECT (100.0f) //we consider unguarded objects 100 times weaker than us
  24. struct BankConfig;
  25. class CBankInfo;
  26. class Engine;
  27. class InputVariable;
  28. class CGTownInstance;
  29. FuzzyHelper * fh;
  30. extern boost::thread_specific_ptr<CCallback> cb;
  31. extern boost::thread_specific_ptr<VCAI> ai;
  32. engineBase::engineBase()
  33. {
  34. engine.addRuleBlock(&rules);
  35. }
  36. void engineBase::configure()
  37. {
  38. engine.configure("Minimum", "Maximum", "Minimum", "AlgebraicSum", "Centroid", "General");
  39. logAi->info(engine.toString());
  40. }
  41. void engineBase::addRule(const std::string & txt)
  42. {
  43. rules.addRule(fl::Rule::parse(txt, &engine));
  44. }
  45. struct armyStructure
  46. {
  47. float walkers, shooters, flyers;
  48. ui32 maxSpeed;
  49. };
  50. armyStructure evaluateArmyStructure(const CArmedInstance * army)
  51. {
  52. ui64 totalStrenght = army->getArmyStrength();
  53. double walkersStrenght = 0;
  54. double flyersStrenght = 0;
  55. double shootersStrenght = 0;
  56. ui32 maxSpeed = 0;
  57. for(auto s : army->Slots())
  58. {
  59. bool walker = true;
  60. if(s.second->type->hasBonusOfType(Bonus::SHOOTER))
  61. {
  62. shootersStrenght += s.second->getPower();
  63. walker = false;
  64. }
  65. if(s.second->type->hasBonusOfType(Bonus::FLYING))
  66. {
  67. flyersStrenght += s.second->getPower();
  68. walker = false;
  69. }
  70. if(walker)
  71. walkersStrenght += s.second->getPower();
  72. vstd::amax(maxSpeed, s.second->type->valOfBonuses(Bonus::STACKS_SPEED));
  73. }
  74. armyStructure as;
  75. as.walkers = walkersStrenght / totalStrenght;
  76. as.shooters = shootersStrenght / totalStrenght;
  77. as.flyers = flyersStrenght / totalStrenght;
  78. as.maxSpeed = maxSpeed;
  79. assert(as.walkers || as.flyers || as.shooters);
  80. return as;
  81. }
  82. FuzzyHelper::FuzzyHelper()
  83. {
  84. initTacticalAdvantage();
  85. ta.configure();
  86. initVisitTile();
  87. vt.configure();
  88. initWanderTarget();
  89. wanderTarget.configure();
  90. }
  91. void FuzzyHelper::initTacticalAdvantage()
  92. {
  93. try
  94. {
  95. ta.ourShooters = new fl::InputVariable("OurShooters");
  96. ta.ourWalkers = new fl::InputVariable("OurWalkers");
  97. ta.ourFlyers = new fl::InputVariable("OurFlyers");
  98. ta.enemyShooters = new fl::InputVariable("EnemyShooters");
  99. ta.enemyWalkers = new fl::InputVariable("EnemyWalkers");
  100. ta.enemyFlyers = new fl::InputVariable("EnemyFlyers");
  101. //Tactical advantage calculation
  102. std::vector<fl::InputVariable *> helper =
  103. {
  104. ta.ourShooters, ta.ourWalkers, ta.ourFlyers, ta.enemyShooters, ta.enemyWalkers, ta.enemyFlyers
  105. };
  106. for(auto val : helper)
  107. {
  108. ta.engine.addInputVariable(val);
  109. val->addTerm(new fl::Ramp("FEW", 0.6, 0.0));
  110. val->addTerm(new fl::Ramp("MANY", 0.4, 1));
  111. val->setRange(0.0, 1.0);
  112. }
  113. ta.ourSpeed = new fl::InputVariable("OurSpeed");
  114. ta.enemySpeed = new fl::InputVariable("EnemySpeed");
  115. helper = {ta.ourSpeed, ta.enemySpeed};
  116. for(auto val : helper)
  117. {
  118. ta.engine.addInputVariable(val);
  119. val->addTerm(new fl::Ramp("LOW", 6.5, 3));
  120. val->addTerm(new fl::Triangle("MEDIUM", 5.5, 10.5));
  121. val->addTerm(new fl::Ramp("HIGH", 8.5, 16));
  122. val->setRange(0, 25);
  123. }
  124. ta.castleWalls = new fl::InputVariable("CastleWalls");
  125. ta.engine.addInputVariable(ta.castleWalls);
  126. {
  127. fl::Rectangle * none = new fl::Rectangle("NONE", CGTownInstance::NONE, CGTownInstance::NONE + (CGTownInstance::FORT - CGTownInstance::NONE) * 0.5f);
  128. ta.castleWalls->addTerm(none);
  129. fl::Trapezoid * medium = new fl::Trapezoid("MEDIUM", (CGTownInstance::FORT - CGTownInstance::NONE) * 0.5f, CGTownInstance::FORT,
  130. CGTownInstance::CITADEL, CGTownInstance::CITADEL + (CGTownInstance::CASTLE - CGTownInstance::CITADEL) * 0.5f);
  131. ta.castleWalls->addTerm(medium);
  132. fl::Ramp * high = new fl::Ramp("HIGH", CGTownInstance::CITADEL - 0.1, CGTownInstance::CASTLE);
  133. ta.castleWalls->addTerm(high);
  134. ta.castleWalls->setRange(CGTownInstance::NONE, CGTownInstance::CASTLE);
  135. }
  136. ta.bankPresent = new fl::InputVariable("Bank");
  137. ta.engine.addInputVariable(ta.bankPresent);
  138. {
  139. fl::Rectangle * termFalse = new fl::Rectangle("FALSE", 0.0, 0.5f);
  140. ta.bankPresent->addTerm(termFalse);
  141. fl::Rectangle * termTrue = new fl::Rectangle("TRUE", 0.5f, 1);
  142. ta.bankPresent->addTerm(termTrue);
  143. ta.bankPresent->setRange(0, 1);
  144. }
  145. ta.threat = new fl::OutputVariable("Threat");
  146. ta.engine.addOutputVariable(ta.threat);
  147. ta.threat->addTerm(new fl::Ramp("LOW", 1, MIN_AI_STRENGHT));
  148. ta.threat->addTerm(new fl::Triangle("MEDIUM", 0.8, 1.2));
  149. ta.threat->addTerm(new fl::Ramp("HIGH", 1, 1.5));
  150. ta.threat->setRange(MIN_AI_STRENGHT, 1.5);
  151. ta.addRule("if OurShooters is MANY and EnemySpeed is LOW then Threat is LOW");
  152. ta.addRule("if OurShooters is MANY and EnemyShooters is FEW then Threat is LOW");
  153. ta.addRule("if OurSpeed is LOW and EnemyShooters is MANY then Threat is HIGH");
  154. ta.addRule("if OurSpeed is HIGH and EnemyShooters is MANY then Threat is LOW");
  155. ta.addRule("if OurWalkers is FEW and EnemyShooters is MANY then Threat is somewhat LOW");
  156. ta.addRule("if OurShooters is MANY and EnemySpeed is HIGH then Threat is somewhat HIGH");
  157. //just to cover all cases
  158. ta.addRule("if OurShooters is FEW and EnemySpeed is HIGH then Threat is MEDIUM");
  159. ta.addRule("if EnemySpeed is MEDIUM then Threat is MEDIUM");
  160. ta.addRule("if EnemySpeed is LOW and OurShooters is FEW then Threat is MEDIUM");
  161. ta.addRule("if Bank is TRUE and OurShooters is MANY then Threat is somewhat HIGH");
  162. ta.addRule("if Bank is TRUE and EnemyShooters is MANY then Threat is LOW");
  163. ta.addRule("if CastleWalls is HIGH and OurWalkers is MANY then Threat is very HIGH");
  164. ta.addRule("if CastleWalls is HIGH and OurFlyers is MANY and OurShooters is MANY then Threat is MEDIUM");
  165. ta.addRule("if CastleWalls is MEDIUM and OurShooters is MANY and EnemyWalkers is MANY then Threat is LOW");
  166. }
  167. catch(fl::Exception & pe)
  168. {
  169. logAi->error("initTacticalAdvantage: %s", pe.getWhat());
  170. }
  171. }
  172. float FuzzyHelper::calculateTurnDistanceInputValue(const CGHeroInstance * h, int3 tile) const
  173. {
  174. float turns = 0.0f;
  175. float distance = CPathfinderHelper::getMovementCost(h, tile);
  176. if(distance)
  177. {
  178. if(distance < h->movement) //we can move there within one turn
  179. turns = (fl::scalar)distance / h->movement;
  180. else
  181. turns = 1 + (fl::scalar)(distance - h->movement) / h->maxMovePoints(true); //bool on land?
  182. }
  183. return turns;
  184. }
  185. ui64 FuzzyHelper::estimateBankDanger(const CBank * bank)
  186. {
  187. //this one is not fuzzy anymore, just calculate weighted average
  188. auto objectInfo = VLC->objtypeh->getHandlerFor(bank->ID, bank->subID)->getObjectInfo(bank->appearance);
  189. CBankInfo * bankInfo = dynamic_cast<CBankInfo *>(objectInfo.get());
  190. ui64 totalStrength = 0;
  191. ui8 totalChance = 0;
  192. for(auto config : bankInfo->getPossibleGuards())
  193. {
  194. totalStrength += config.second.totalStrength * config.first;
  195. totalChance += config.first;
  196. }
  197. return totalStrength / std::max<ui8>(totalChance, 1); //avoid division by zero
  198. }
  199. float FuzzyHelper::getTacticalAdvantage(const CArmedInstance * we, const CArmedInstance * enemy)
  200. {
  201. float output = 1;
  202. try
  203. {
  204. armyStructure ourStructure = evaluateArmyStructure(we);
  205. armyStructure enemyStructure = evaluateArmyStructure(enemy);
  206. ta.ourWalkers->setValue(ourStructure.walkers);
  207. ta.ourShooters->setValue(ourStructure.shooters);
  208. ta.ourFlyers->setValue(ourStructure.flyers);
  209. ta.ourSpeed->setValue(ourStructure.maxSpeed);
  210. ta.enemyWalkers->setValue(enemyStructure.walkers);
  211. ta.enemyShooters->setValue(enemyStructure.shooters);
  212. ta.enemyFlyers->setValue(enemyStructure.flyers);
  213. ta.enemySpeed->setValue(enemyStructure.maxSpeed);
  214. bool bank = dynamic_cast<const CBank *>(enemy);
  215. if(bank)
  216. ta.bankPresent->setValue(1);
  217. else
  218. ta.bankPresent->setValue(0);
  219. const CGTownInstance * fort = dynamic_cast<const CGTownInstance *>(enemy);
  220. if(fort)
  221. ta.castleWalls->setValue(fort->fortLevel());
  222. else
  223. ta.castleWalls->setValue(0);
  224. //engine.process(TACTICAL_ADVANTAGE);//TODO: Process only Tactical_Advantage
  225. ta.engine.process();
  226. output = ta.threat->getValue();
  227. }
  228. catch(fl::Exception & fe)
  229. {
  230. logAi->error("getTacticalAdvantage: %s ", fe.getWhat());
  231. }
  232. if(output < 0 || (output != output))
  233. {
  234. fl::InputVariable * tab[] = {ta.bankPresent, ta.castleWalls, ta.ourWalkers, ta.ourShooters, ta.ourFlyers, ta.ourSpeed, ta.enemyWalkers, ta.enemyShooters, ta.enemyFlyers, ta.enemySpeed};
  235. std::string names[] = {"bankPresent", "castleWalls", "ourWalkers", "ourShooters", "ourFlyers", "ourSpeed", "enemyWalkers", "enemyShooters", "enemyFlyers", "enemySpeed" };
  236. std::stringstream log("Warning! Fuzzy engine doesn't cover this set of parameters: ");
  237. for(int i = 0; i < boost::size(tab); i++)
  238. log << names[i] << ": " << tab[i]->getValue() << " ";
  239. logAi->error(log.str());
  240. assert(false);
  241. }
  242. return output;
  243. }
  244. float FuzzyHelper::getWanderTargetObjectValue(const CGHeroInstance & h, const ObjectIdRef & obj)
  245. {
  246. float distFromObject = calculateTurnDistanceInputValue(&h, obj->pos);
  247. boost::optional<int> objValueKnownByAI = MapObjectsEvaluator::getInstance().getObjectValue(obj->ID, obj->subID);
  248. int objValue = 0;
  249. if(objValueKnownByAI != boost::none) //consider adding value manipulation based on object instances on map
  250. {
  251. objValue = std::min(std::max(objValueKnownByAI.get(), 0), 20000);
  252. }
  253. else
  254. {
  255. MapObjectsEvaluator::getInstance().addObjectData(obj->ID, obj->subID, 0);
  256. logGlobal->warn("AI met object type it doesn't know - ID: " + std::to_string(obj->ID) + ", subID: " + std::to_string(obj->subID) + " - adding to database with value " + std::to_string(objValue));
  257. }
  258. float output = -1.0f;
  259. try
  260. {
  261. wanderTarget.distance->setValue(distFromObject);
  262. wanderTarget.objectValue->setValue(objValue);
  263. wanderTarget.engine.process();
  264. output = wanderTarget.visitGain->getValue();
  265. }
  266. catch (fl::Exception & fe)
  267. {
  268. logAi->error("evaluate getWanderTargetObjectValue: %s", fe.getWhat());
  269. }
  270. assert(output >= 0.0f);
  271. return output;
  272. }
  273. FuzzyHelper::TacticalAdvantage::~TacticalAdvantage()
  274. {
  275. //TODO: smart pointers?
  276. delete ourWalkers;
  277. delete ourShooters;
  278. delete ourFlyers;
  279. delete enemyWalkers;
  280. delete enemyShooters;
  281. delete enemyFlyers;
  282. delete ourSpeed;
  283. delete enemySpeed;
  284. delete bankPresent;
  285. delete castleWalls;
  286. delete threat;
  287. }
  288. //std::shared_ptr<AbstractGoal> chooseSolution (std::vector<std::shared_ptr<AbstractGoal>> & vec)
  289. Goals::TSubgoal FuzzyHelper::chooseSolution(Goals::TGoalVec vec)
  290. {
  291. if(vec.empty()) //no possibilities found
  292. return sptr(Goals::Invalid());
  293. ai->cachedSectorMaps.clear();
  294. //a trick to switch between heroes less often - calculatePaths is costly
  295. auto sortByHeroes = [](const Goals::TSubgoal & lhs, const Goals::TSubgoal & rhs) -> bool
  296. {
  297. return lhs->hero.h < rhs->hero.h;
  298. };
  299. boost::sort(vec, sortByHeroes);
  300. for(auto g : vec)
  301. {
  302. setPriority(g);
  303. }
  304. auto compareGoals = [](const Goals::TSubgoal & lhs, const Goals::TSubgoal & rhs) -> bool
  305. {
  306. return lhs->priority < rhs->priority;
  307. };
  308. return *boost::max_element(vec, compareGoals);
  309. }
  310. float FuzzyHelper::evaluate(Goals::Explore & g)
  311. {
  312. return 1;
  313. }
  314. float FuzzyHelper::evaluate(Goals::RecruitHero & g)
  315. {
  316. return 1;
  317. }
  318. FuzzyHelper::EvalVisitTile::~EvalVisitTile()
  319. {
  320. delete strengthRatio;
  321. delete heroStrength;
  322. delete turnDistance;
  323. delete missionImportance;
  324. delete estimatedReward;
  325. }
  326. void FuzzyHelper::initVisitTile()
  327. {
  328. try
  329. {
  330. vt.strengthRatio = new fl::InputVariable("strengthRatio"); //hero must be strong enough to defeat guards
  331. vt.heroStrength = new fl::InputVariable("heroStrength"); //we want to use weakest possible hero
  332. vt.turnDistance = new fl::InputVariable("turnDistance"); //we want to use hero who is near
  333. vt.missionImportance = new fl::InputVariable("lockedMissionImportance"); //we may want to preempt hero with low-priority mission
  334. vt.estimatedReward = new fl::InputVariable("estimatedReward"); //indicate AI that content of the file is important or it is probably bad
  335. vt.value = new fl::OutputVariable("Value");
  336. vt.value->setMinimum(0);
  337. vt.value->setMaximum(5);
  338. std::vector<fl::InputVariable *> helper = {vt.strengthRatio, vt.heroStrength, vt.turnDistance, vt.missionImportance, vt.estimatedReward};
  339. for(auto val : helper)
  340. {
  341. vt.engine.addInputVariable(val);
  342. }
  343. vt.engine.addOutputVariable(vt.value);
  344. vt.strengthRatio->addTerm(new fl::Ramp("LOW", SAFE_ATTACK_CONSTANT, 0));
  345. vt.strengthRatio->addTerm(new fl::Ramp("HIGH", SAFE_ATTACK_CONSTANT, SAFE_ATTACK_CONSTANT * 3));
  346. vt.strengthRatio->setRange(0, SAFE_ATTACK_CONSTANT * 3);
  347. //strength compared to our main hero
  348. vt.heroStrength->addTerm(new fl::Ramp("LOW", 0.2, 0));
  349. vt.heroStrength->addTerm(new fl::Triangle("MEDIUM", 0.2, 0.8));
  350. vt.heroStrength->addTerm(new fl::Ramp("HIGH", 0.5, 1));
  351. vt.heroStrength->setRange(0.0, 1.0);
  352. vt.turnDistance->addTerm(new fl::Ramp("SMALL", 0.5, 0));
  353. vt.turnDistance->addTerm(new fl::Triangle("MEDIUM", 0.1, 0.8));
  354. vt.turnDistance->addTerm(new fl::Ramp("LONG", 0.5, 3));
  355. vt.turnDistance->setRange(0.0, 3.0);
  356. vt.missionImportance->addTerm(new fl::Ramp("LOW", 2.5, 0));
  357. vt.missionImportance->addTerm(new fl::Triangle("MEDIUM", 2, 3));
  358. vt.missionImportance->addTerm(new fl::Ramp("HIGH", 2.5, 5));
  359. vt.missionImportance->setRange(0.0, 5.0);
  360. vt.estimatedReward->addTerm(new fl::Ramp("LOW", 2.5, 0));
  361. vt.estimatedReward->addTerm(new fl::Ramp("HIGH", 2.5, 5));
  362. vt.estimatedReward->setRange(0.0, 5.0);
  363. //an issue: in 99% cases this outputs center of mass (2.5) regardless of actual input :/
  364. //should be same as "mission Importance" to keep consistency
  365. vt.value->addTerm(new fl::Ramp("LOW", 2.5, 0));
  366. vt.value->addTerm(new fl::Triangle("MEDIUM", 2, 3)); //can't be center of mass :/
  367. vt.value->addTerm(new fl::Ramp("HIGH", 2.5, 5));
  368. vt.value->setRange(0.0, 5.0);
  369. //use unarmed scouts if possible
  370. vt.addRule("if strengthRatio is HIGH and heroStrength is LOW then Value is very HIGH");
  371. //we may want to use secondary hero(es) rather than main hero
  372. vt.addRule("if strengthRatio is HIGH and heroStrength is MEDIUM then Value is somewhat HIGH");
  373. vt.addRule("if strengthRatio is HIGH and heroStrength is HIGH then Value is somewhat LOW");
  374. //don't assign targets to heroes who are too weak, but prefer targets of our main hero (in case we need to gather army)
  375. vt.addRule("if strengthRatio is LOW and heroStrength is LOW then Value is very LOW");
  376. //attempt to arm secondary heroes is not stupid
  377. vt.addRule("if strengthRatio is LOW and heroStrength is MEDIUM then Value is somewhat HIGH");
  378. vt.addRule("if strengthRatio is LOW and heroStrength is HIGH then Value is LOW");
  379. //do not cancel important goals
  380. vt.addRule("if lockedMissionImportance is HIGH then Value is very LOW");
  381. vt.addRule("if lockedMissionImportance is MEDIUM then Value is somewhat LOW");
  382. vt.addRule("if lockedMissionImportance is LOW then Value is HIGH");
  383. //pick nearby objects if it's easy, avoid long walks
  384. vt.addRule("if turnDistance is SMALL then Value is HIGH");
  385. vt.addRule("if turnDistance is MEDIUM then Value is MEDIUM");
  386. vt.addRule("if turnDistance is LONG then Value is LOW");
  387. //some goals are more rewarding by definition f.e. capturing town is more important than collecting resource - experimental
  388. vt.addRule("if estimatedReward is HIGH then Value is very HIGH");
  389. vt.addRule("if estimatedReward is LOW then Value is somewhat LOW");
  390. }
  391. catch(fl::Exception & fe)
  392. {
  393. logAi->error("visitTile: %s", fe.getWhat());
  394. }
  395. }
  396. void FuzzyHelper::initWanderTarget()
  397. {
  398. try
  399. {
  400. wanderTarget.distance = new fl::InputVariable("distance"); //distance on map from object
  401. wanderTarget.objectValue = new fl::InputVariable("objectValue"); //value of that object type known by AI
  402. wanderTarget.visitGain = new fl::OutputVariable("visitGain");
  403. wanderTarget.visitGain->setMinimum(0);
  404. wanderTarget.visitGain->setMaximum(10);
  405. wanderTarget.engine.addInputVariable(wanderTarget.distance);
  406. wanderTarget.engine.addInputVariable(wanderTarget.objectValue);
  407. wanderTarget.engine.addOutputVariable(wanderTarget.visitGain);
  408. //for now distance variable same as in as VisitTile
  409. wanderTarget.distance->addTerm(new fl::Ramp("SHORT", 0.5, 0));
  410. wanderTarget.distance->addTerm(new fl::Triangle("MEDIUM", 0.1, 0.8));
  411. wanderTarget.distance->addTerm(new fl::Ramp("LONG", 0.5, 3));
  412. wanderTarget.distance->setRange(0, 3.0);
  413. //objectValue ranges are based on checking RMG priorities of some objects and trying to guess sane value ranges
  414. wanderTarget.objectValue->addTerm(new fl::Ramp("LOW", 3000, 0)); //I have feeling that concave shape might work well instead of ramp for objectValue FL terms
  415. wanderTarget.objectValue->addTerm(new fl::Triangle("MEDIUM", 2500, 6000));
  416. wanderTarget.objectValue->addTerm(new fl::Ramp("HIGH", 5000, 20000));
  417. wanderTarget.objectValue->setRange(0, 20000); //relic artifact value is border value by design, even better things are scaled down.
  418. wanderTarget.visitGain->addTerm(new fl::Ramp("LOW", 5, 0));
  419. wanderTarget.visitGain->addTerm(new fl::Triangle("MEDIUM", 4, 6));
  420. wanderTarget.visitGain->addTerm(new fl::Ramp("HIGH", 5, 10));
  421. wanderTarget.visitGain->setRange(0, 10);
  422. wanderTarget.addRule("if distance is LONG and objectValue is HIGH then visitGain is MEDIUM");
  423. wanderTarget.addRule("if distance is MEDIUM and objectValue is HIGH then visitGain is somewhat HIGH");
  424. wanderTarget.addRule("if distance is SHORT and objectValue is HIGH then visitGain is HIGH");
  425. wanderTarget.addRule("if distance is LONG and objectValue is MEDIUM then visitGain is somewhat LOW");
  426. wanderTarget.addRule("if distance is MEDIUM and objectValue is MEDIUM then visitGain is MEDIUM");
  427. wanderTarget.addRule("if distance is SHORT and objectValue is MEDIUM then visitGain is somewhat HIGH");
  428. wanderTarget.addRule("if distance is LONG and objectValue is LOW then visitGain is very LOW");
  429. wanderTarget.addRule("if distance is MEDIUM and objectValue is LOW then visitGain is LOW");
  430. wanderTarget.addRule("if distance is SHORT and objectValue is LOW then visitGain is MEDIUM");
  431. }
  432. catch(fl::Exception & fe)
  433. {
  434. logAi->error("FindWanderTarget: %s", fe.getWhat());
  435. }
  436. }
  437. float FuzzyHelper::evaluate(Goals::VisitTile & g)
  438. {
  439. //we assume that hero is already set and we want to choose most suitable one for the mission
  440. if(!g.hero)
  441. return 0;
  442. //assert(cb->isInTheMap(g.tile));
  443. float turns = calculateTurnDistanceInputValue(g.hero.h, g.tile);
  444. float missionImportance = 0;
  445. if(vstd::contains(ai->lockedHeroes, g.hero))
  446. missionImportance = ai->lockedHeroes[g.hero]->priority;
  447. float strengthRatio = 10.0f; //we are much stronger than enemy
  448. ui64 danger = evaluateDanger(g.tile, g.hero.h);
  449. if(danger)
  450. strengthRatio = (fl::scalar)g.hero.h->getTotalStrength() / danger;
  451. float tilePriority = 0;
  452. if(g.objid == -1)
  453. {
  454. vt.estimatedReward->setEnabled(false);
  455. }
  456. else if(g.objid == Obj::TOWN) //TODO: move to getObj eventually and add appropiate logic there
  457. {
  458. vt.estimatedReward->setEnabled(true);
  459. tilePriority = 5;
  460. }
  461. try
  462. {
  463. vt.strengthRatio->setValue(strengthRatio);
  464. vt.heroStrength->setValue((fl::scalar)g.hero->getTotalStrength() / ai->primaryHero()->getTotalStrength());
  465. vt.turnDistance->setValue(turns);
  466. vt.missionImportance->setValue(missionImportance);
  467. vt.estimatedReward->setValue(tilePriority);
  468. vt.engine.process();
  469. //engine.process(VISIT_TILE); //TODO: Process only Visit_Tile
  470. g.priority = vt.value->getValue();
  471. }
  472. catch(fl::Exception & fe)
  473. {
  474. logAi->error("evaluate VisitTile: %s", fe.getWhat());
  475. }
  476. assert(g.priority >= 0);
  477. return g.priority;
  478. }
  479. float FuzzyHelper::evaluate(Goals::VisitHero & g)
  480. {
  481. auto obj = cb->getObj(ObjectInstanceID(g.objid)); //we assume for now that these goals are similar
  482. if(!obj)
  483. return -100; //hero died in the meantime
  484. //TODO: consider direct copy (constructor?)
  485. g.setpriority(Goals::VisitTile(obj->visitablePos()).sethero(g.hero).setisAbstract(g.isAbstract).accept(this));
  486. return g.priority;
  487. }
  488. float FuzzyHelper::evaluate(Goals::GatherArmy & g)
  489. {
  490. //the more army we need, the more important goal
  491. //the more army we lack, the less important goal
  492. float army = g.hero->getArmyStrength();
  493. float ratio = g.value / std::max(g.value - army, 2000.0f); //2000 is about the value of hero recruited from tavern
  494. return 5 * (ratio / (ratio + 2)); //so 50% army gives 2.5, asymptotic 5
  495. }
  496. float FuzzyHelper::evaluate(Goals::ClearWayTo & g)
  497. {
  498. if(!g.hero.h)
  499. throw cannotFulfillGoalException("ClearWayTo called without hero!");
  500. int3 t = ai->getCachedSectorMap(g.hero)->firstTileToGet(g.hero, g.tile);
  501. if(t.valid())
  502. {
  503. if(isSafeToVisit(g.hero, t))
  504. {
  505. g.setpriority(Goals::VisitTile(g.tile).sethero(g.hero).setisAbstract(g.isAbstract).accept(this));
  506. }
  507. else
  508. {
  509. g.setpriority (Goals::GatherArmy(evaluateDanger(t, g.hero.h)*SAFE_ATTACK_CONSTANT).
  510. sethero(g.hero).setisAbstract(true).accept(this));
  511. }
  512. return g.priority;
  513. }
  514. else
  515. return -1;
  516. }
  517. float FuzzyHelper::evaluate(Goals::BuildThis & g)
  518. {
  519. return g.priority; //TODO
  520. }
  521. float FuzzyHelper::evaluate(Goals::DigAtTile & g)
  522. {
  523. return 0;
  524. }
  525. float FuzzyHelper::evaluate(Goals::CollectRes & g)
  526. {
  527. return g.priority; //handled by ResourceManager
  528. }
  529. float FuzzyHelper::evaluate(Goals::Build & g)
  530. {
  531. return 0;
  532. }
  533. float FuzzyHelper::evaluate(Goals::BuyArmy & g)
  534. {
  535. return g.priority;
  536. }
  537. float FuzzyHelper::evaluate(Goals::Invalid & g)
  538. {
  539. return -1e10;
  540. }
  541. float FuzzyHelper::evaluate(Goals::AbstractGoal & g)
  542. {
  543. logAi->warn("Cannot evaluate goal %s", g.name());
  544. return g.priority;
  545. }
  546. void FuzzyHelper::setPriority(Goals::TSubgoal & g) //calls evaluate - Visitor pattern
  547. {
  548. g->setpriority(g->accept(this)); //this enforces returned value is set
  549. }
  550. FuzzyHelper::EvalWanderTargetObject::~EvalWanderTargetObject()
  551. {
  552. delete distance;
  553. delete objectValue;
  554. delete visitGain;
  555. }