FuzzyEngines.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. /*
  2. * FuzzyEngines.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 "FuzzyEngines.h"
  12. #include "Goals/Goals.h"
  13. #include "../../lib/mapObjects/MapObjects.h"
  14. #include "VCAI.h"
  15. #include "MapObjectsEvaluator.h"
  16. #define MIN_AI_STRENGTH (0.5f) //lower when combat AI gets smarter
  17. #define UNGUARDED_OBJECT (100.0f) //we consider unguarded objects 100 times weaker than us
  18. engineBase::engineBase()
  19. {
  20. rules = new fl::RuleBlock();
  21. engine.addRuleBlock(rules);
  22. }
  23. void engineBase::configure()
  24. {
  25. engine.configure("Minimum", "Maximum", "Minimum", "AlgebraicSum", "Centroid", "Proportional");
  26. logAi->trace(engine.toString());
  27. }
  28. void engineBase::addRule(const std::string & txt)
  29. {
  30. rules->addRule(fl::Rule::parse(txt, &engine));
  31. }
  32. struct armyStructure
  33. {
  34. float walkers;
  35. float shooters;
  36. float flyers;
  37. ui32 maxSpeed;
  38. };
  39. armyStructure evaluateArmyStructure(const CArmedInstance * army)
  40. {
  41. ui64 totalStrength = army->getArmyStrength();
  42. double walkersStrength = 0;
  43. double flyersStrength = 0;
  44. double shootersStrength = 0;
  45. ui32 maxSpeed = 0;
  46. static const CSelector selectorSHOOTER = Selector::type()(BonusType::SHOOTER);
  47. static const std::string keySHOOTER = "type_"+std::to_string((int32_t)BonusType::SHOOTER);
  48. static const CSelector selectorFLYING = Selector::type()(BonusType::FLYING);
  49. static const std::string keyFLYING = "type_"+std::to_string((int32_t)BonusType::FLYING);
  50. static const CSelector selectorSTACKS_SPEED = Selector::type()(BonusType::STACKS_SPEED);
  51. static const std::string keySTACKS_SPEED = "type_"+std::to_string((int32_t)BonusType::STACKS_SPEED);
  52. for(const auto & s : army->Slots())
  53. {
  54. bool walker = true;
  55. auto bearer = s.second->getType()->getBonusBearer();
  56. if(bearer->hasBonus(selectorSHOOTER, keySHOOTER))
  57. {
  58. shootersStrength += s.second->getPower();
  59. walker = false;
  60. }
  61. if(bearer->hasBonus(selectorFLYING, keyFLYING))
  62. {
  63. flyersStrength += s.second->getPower();
  64. walker = false;
  65. }
  66. if(walker)
  67. walkersStrength += s.second->getPower();
  68. vstd::amax(maxSpeed, bearer->valOfBonuses(selectorSTACKS_SPEED, keySTACKS_SPEED));
  69. }
  70. armyStructure as;
  71. as.walkers = static_cast<float>(walkersStrength / totalStrength);
  72. as.shooters = static_cast<float>(shootersStrength / totalStrength);
  73. as.flyers = static_cast<float>(flyersStrength / totalStrength);
  74. as.maxSpeed = maxSpeed;
  75. assert(as.walkers || as.flyers || as.shooters);
  76. return as;
  77. }
  78. float HeroMovementGoalEngineBase::calculateTurnDistanceInputValue(const Goals::AbstractGoal & goal) const
  79. {
  80. if(goal.evaluationContext.movementCost > 0)
  81. {
  82. return goal.evaluationContext.movementCost;
  83. }
  84. else
  85. {
  86. auto pathInfo = ai->getPathsInfo(goal.hero.h)->getPathInfo(goal.tile);
  87. return pathInfo->getCost();
  88. }
  89. }
  90. TacticalAdvantageEngine::TacticalAdvantageEngine()
  91. {
  92. try
  93. {
  94. ourShooters = new fl::InputVariable("OurShooters");
  95. ourWalkers = new fl::InputVariable("OurWalkers");
  96. ourFlyers = new fl::InputVariable("OurFlyers");
  97. enemyShooters = new fl::InputVariable("EnemyShooters");
  98. enemyWalkers = new fl::InputVariable("EnemyWalkers");
  99. enemyFlyers = new fl::InputVariable("EnemyFlyers");
  100. //Tactical advantage calculation
  101. std::vector<fl::InputVariable *> helper =
  102. {
  103. ourShooters, ourWalkers, ourFlyers, enemyShooters, enemyWalkers, enemyFlyers
  104. };
  105. for(auto val : helper)
  106. {
  107. engine.addInputVariable(val);
  108. val->addTerm(new fl::Ramp("FEW", 0.6, 0.0));
  109. val->addTerm(new fl::Ramp("MANY", 0.4, 1));
  110. val->setRange(0.0, 1.0);
  111. }
  112. ourSpeed = new fl::InputVariable("OurSpeed");
  113. enemySpeed = new fl::InputVariable("EnemySpeed");
  114. helper = { ourSpeed, enemySpeed };
  115. for(auto val : helper)
  116. {
  117. engine.addInputVariable(val);
  118. val->addTerm(new fl::Ramp("LOW", 6.5, 3));
  119. val->addTerm(new fl::Triangle("MEDIUM", 5.5, 10.5));
  120. val->addTerm(new fl::Ramp("HIGH", 8.5, 16));
  121. val->setRange(0, 25);
  122. }
  123. castleWalls = new fl::InputVariable("CastleWalls");
  124. engine.addInputVariable(castleWalls);
  125. {
  126. int wallsNone = CGTownInstance::NONE;
  127. int wallsFort = CGTownInstance::FORT;
  128. int wallsCitadel = CGTownInstance::CITADEL;
  129. int wallsCastle = CGTownInstance::CASTLE;
  130. fl::Rectangle * none = new fl::Rectangle("NONE", wallsNone, wallsNone + (wallsFort - wallsNone) * 0.5f);
  131. castleWalls->addTerm(none);
  132. fl::Trapezoid * medium = new fl::Trapezoid("MEDIUM", (wallsFort - wallsNone) * 0.5f, wallsFort, wallsCitadel, wallsCitadel + (wallsCastle - wallsCitadel) * 0.5f);
  133. castleWalls->addTerm(medium);
  134. fl::Ramp * high = new fl::Ramp("HIGH", wallsCitadel - 0.1, wallsCastle);
  135. castleWalls->addTerm(high);
  136. castleWalls->setRange(wallsNone, wallsCastle);
  137. }
  138. bankPresent = new fl::InputVariable("Bank");
  139. engine.addInputVariable(bankPresent);
  140. {
  141. fl::Rectangle * termFalse = new fl::Rectangle("FALSE", 0.0, 0.5f);
  142. bankPresent->addTerm(termFalse);
  143. fl::Rectangle * termTrue = new fl::Rectangle("TRUE", 0.5f, 1);
  144. bankPresent->addTerm(termTrue);
  145. bankPresent->setRange(0, 1);
  146. }
  147. threat = new fl::OutputVariable("Threat");
  148. engine.addOutputVariable(threat);
  149. threat->addTerm(new fl::Ramp("LOW", 1, MIN_AI_STRENGTH));
  150. threat->addTerm(new fl::Triangle("MEDIUM", 0.8, 1.2));
  151. threat->addTerm(new fl::Ramp("HIGH", 1, 1.5));
  152. threat->setRange(MIN_AI_STRENGTH, 1.5);
  153. addRule("if OurShooters is MANY and EnemySpeed is LOW then Threat is LOW");
  154. addRule("if OurShooters is MANY and EnemyShooters is FEW then Threat is LOW");
  155. addRule("if OurSpeed is LOW and EnemyShooters is MANY then Threat is HIGH");
  156. addRule("if OurSpeed is HIGH and EnemyShooters is MANY then Threat is LOW");
  157. addRule("if OurWalkers is FEW and EnemyShooters is MANY then Threat is LOW");
  158. addRule("if OurShooters is MANY and EnemySpeed is HIGH then Threat is HIGH");
  159. //just to cover all cases
  160. addRule("if OurShooters is FEW and EnemySpeed is HIGH then Threat is MEDIUM");
  161. addRule("if EnemySpeed is MEDIUM then Threat is MEDIUM");
  162. addRule("if EnemySpeed is LOW and OurShooters is FEW then Threat is MEDIUM");
  163. addRule("if Bank is TRUE and OurShooters is MANY then Threat is HIGH");
  164. addRule("if Bank is TRUE and EnemyShooters is MANY then Threat is LOW");
  165. addRule("if CastleWalls is HIGH and OurWalkers is MANY then Threat is HIGH");
  166. addRule("if CastleWalls is HIGH and OurFlyers is MANY and OurShooters is MANY then Threat is MEDIUM");
  167. addRule("if CastleWalls is MEDIUM and OurShooters is MANY and EnemyWalkers is MANY then Threat is LOW");
  168. }
  169. catch(fl::Exception & pe)
  170. {
  171. logAi->error("initTacticalAdvantage: %s", pe.getWhat());
  172. }
  173. configure();
  174. }
  175. float TacticalAdvantageEngine::getTacticalAdvantage(const CArmedInstance * we, const CArmedInstance * enemy)
  176. {
  177. float output = 1;
  178. /*try //TODO: rework this engine, it tends to produce nonsense output
  179. {
  180. armyStructure ourStructure = evaluateArmyStructure(we);
  181. armyStructure enemyStructure = evaluateArmyStructure(enemy);
  182. ourWalkers->setValue(ourStructure.walkers);
  183. ourShooters->setValue(ourStructure.shooters);
  184. ourFlyers->setValue(ourStructure.flyers);
  185. ourSpeed->setValue(ourStructure.maxSpeed);
  186. enemyWalkers->setValue(enemyStructure.walkers);
  187. enemyShooters->setValue(enemyStructure.shooters);
  188. enemyFlyers->setValue(enemyStructure.flyers);
  189. enemySpeed->setValue(enemyStructure.maxSpeed);
  190. const CGTownInstance * fort = dynamic_cast<const CGTownInstance *>(enemy);
  191. if(fort)
  192. castleWalls->setValue(fort->fortLevel());
  193. else
  194. castleWalls->setValue(0);
  195. engine.process();
  196. output = threat->getValue();
  197. }
  198. catch(fl::Exception & fe)
  199. {
  200. logAi->error("getTacticalAdvantage: %s ", fe.getWhat());
  201. }
  202. if(output < 0 || (output != output))
  203. {
  204. fl::InputVariable * tab[] = { bankPresent, castleWalls, ourWalkers, ourShooters, ourFlyers, ourSpeed, enemyWalkers, enemyShooters, enemyFlyers, enemySpeed };
  205. std::string names[] = { "bankPresent", "castleWalls", "ourWalkers", "ourShooters", "ourFlyers", "ourSpeed", "enemyWalkers", "enemyShooters", "enemyFlyers", "enemySpeed" };
  206. std::stringstream log("Warning! Fuzzy engine doesn't cover this set of parameters: ");
  207. for(int i = 0; i < boost::size(tab); i++)
  208. log << names[i] << ": " << tab[i]->getValue() << " ";
  209. logAi->error(log.str());
  210. assert(false);
  211. }*/
  212. return output;
  213. }
  214. //std::shared_ptr<AbstractGoal> chooseSolution (std::vector<std::shared_ptr<AbstractGoal>> & vec)
  215. HeroMovementGoalEngineBase::HeroMovementGoalEngineBase()
  216. {
  217. try
  218. {
  219. strengthRatio = new fl::InputVariable("strengthRatio"); //hero must be strong enough to defeat guards
  220. heroStrength = new fl::InputVariable("heroStrength"); //we want to use weakest possible hero
  221. turnDistance = new fl::InputVariable("turnDistance"); //we want to use hero who is near
  222. missionImportance = new fl::InputVariable("lockedMissionImportance"); //we may want to preempt hero with low-priority mission
  223. value = new fl::OutputVariable("Value");
  224. value->setMinimum(0);
  225. value->setMaximum(5);
  226. std::vector<fl::InputVariable *> helper = { strengthRatio, heroStrength, turnDistance, missionImportance };
  227. for(auto val : helper)
  228. {
  229. engine.addInputVariable(val);
  230. }
  231. engine.addOutputVariable(value);
  232. strengthRatio->addTerm(new fl::Ramp("LOW", SAFE_ATTACK_CONSTANT, 0));
  233. strengthRatio->addTerm(new fl::Ramp("HIGH", SAFE_ATTACK_CONSTANT, SAFE_ATTACK_CONSTANT * 3));
  234. strengthRatio->setRange(0, SAFE_ATTACK_CONSTANT * 3);
  235. //strength compared to our main hero
  236. heroStrength->addTerm(new fl::Ramp("LOW", 0.5, 0));
  237. heroStrength->addTerm(new fl::Triangle("MEDIUM", 0.2, 0.8));
  238. heroStrength->addTerm(new fl::Ramp("HIGH", 0.5, 1));
  239. heroStrength->setRange(0.0, 1.0);
  240. turnDistance->addTerm(new fl::Ramp("SHORT", 0.5, 0));
  241. turnDistance->addTerm(new fl::Triangle("MEDIUM", 0.1, 0.8));
  242. turnDistance->addTerm(new fl::Ramp("LONG", 0.5, 10));
  243. turnDistance->setRange(0.0, 10.0);
  244. missionImportance->addTerm(new fl::Ramp("LOW", 2.5, 0));
  245. missionImportance->addTerm(new fl::Triangle("MEDIUM", 2, 3));
  246. missionImportance->addTerm(new fl::Ramp("HIGH", 2.5, 5));
  247. missionImportance->setRange(0.0, 5.0);
  248. //an issue: in 99% cases this outputs center of mass (2.5) regardless of actual input :/
  249. //should be same as "mission Importance" to keep consistency
  250. value->addTerm(new fl::Ramp("LOW", 2.5, 0));
  251. value->addTerm(new fl::Triangle("MEDIUM", 2, 3)); //can't be center of mass :/
  252. value->addTerm(new fl::Ramp("HIGH", 2.5, 5));
  253. value->setRange(0.0, 5.0);
  254. //use unarmed scouts if possible
  255. addRule("if strengthRatio is HIGH and heroStrength is LOW then Value is HIGH");
  256. //we may want to use secondary hero(es) rather than main hero
  257. addRule("if strengthRatio is HIGH and heroStrength is MEDIUM then Value is MEDIUM");
  258. addRule("if strengthRatio is HIGH and heroStrength is HIGH then Value is LOW");
  259. //don't assign targets to heroes who are too weak, but prefer targets of our main hero (in case we need to gather army)
  260. addRule("if strengthRatio is LOW and heroStrength is LOW then Value is LOW");
  261. //attempt to arm secondary heroes is not stupid
  262. addRule("if strengthRatio is LOW and heroStrength is MEDIUM then Value is HIGH");
  263. addRule("if strengthRatio is LOW and heroStrength is HIGH then Value is LOW");
  264. //do not cancel important goals
  265. addRule("if lockedMissionImportance is HIGH then Value is LOW");
  266. addRule("if lockedMissionImportance is MEDIUM then Value is MEDIUM");
  267. addRule("if lockedMissionImportance is LOW then Value is HIGH");
  268. //pick nearby objects if it's easy, avoid long walks
  269. addRule("if turnDistance is SHORT then Value is HIGH");
  270. addRule("if turnDistance is MEDIUM then Value is MEDIUM");
  271. addRule("if turnDistance is LONG then Value is LOW");
  272. }
  273. catch(fl::Exception & fe)
  274. {
  275. logAi->error("HeroMovementGoalEngineBase: %s", fe.getWhat());
  276. }
  277. }
  278. void HeroMovementGoalEngineBase::setSharedFuzzyVariables(Goals::AbstractGoal & goal)
  279. {
  280. float turns = calculateTurnDistanceInputValue(goal);
  281. float missionImportanceData = 0;
  282. if(vstd::contains(ai->lockedHeroes, goal.hero))
  283. {
  284. missionImportanceData = ai->lockedHeroes[goal.hero]->priority;
  285. }
  286. else if(goal.parent)
  287. {
  288. missionImportanceData = goal.parent->priority;
  289. }
  290. float strengthRatioData = 10.0f; //we are much stronger than enemy
  291. ui64 danger = fh->evaluateDanger(goal.tile, goal.hero.h);
  292. if(danger)
  293. strengthRatioData = static_cast<float>((fl::scalar)goal.hero.h->getTotalStrength() / danger);
  294. try
  295. {
  296. strengthRatio->setValue(strengthRatioData);
  297. heroStrength->setValue((fl::scalar)goal.hero->getTotalStrength() / ai->primaryHero()->getTotalStrength());
  298. turnDistance->setValue(turns);
  299. missionImportance->setValue(missionImportanceData);
  300. }
  301. catch(fl::Exception & fe)
  302. {
  303. logAi->error("HeroMovementGoalEngineBase::setSharedFuzzyVariables: %s", fe.getWhat());
  304. }
  305. }
  306. VisitObjEngine::VisitObjEngine()
  307. {
  308. try
  309. {
  310. objectValue = new fl::InputVariable("objectValue"); //value of that object type known by AI
  311. engine.addInputVariable(objectValue);
  312. //objectValue ranges are based on checking RMG priorities of some objects and checking LOW/MID/HIGH proportions for various values in QtFuzzyLite
  313. objectValue->addTerm(new fl::Ramp("LOW", 3500.0, 0.0));
  314. objectValue->addTerm(new fl::Triangle("MEDIUM", 0.0, 8500.0));
  315. std::vector<fl::Discrete::Pair> multiRamp = { fl::Discrete::Pair(5000.0, 0.0), fl::Discrete::Pair(10000.0, 0.75), fl::Discrete::Pair(20000.0, 1.0) };
  316. objectValue->addTerm(new fl::Discrete("HIGH", multiRamp));
  317. objectValue->setRange(0.0, 20000.0); //relic artifact value is border value by design, even better things are scaled down.
  318. addRule("if objectValue is HIGH then Value is HIGH");
  319. addRule("if objectValue is MEDIUM then Value is MEDIUM");
  320. addRule("if objectValue is LOW then Value is LOW");
  321. }
  322. catch(fl::Exception & fe)
  323. {
  324. logAi->error("FindWanderTarget: %s", fe.getWhat());
  325. }
  326. configure();
  327. }
  328. float VisitObjEngine::evaluate(Goals::VisitObj & goal)
  329. {
  330. if(!goal.hero)
  331. return 0;
  332. auto obj = ai->myCb->getObj(ObjectInstanceID(goal.objid));
  333. if(!obj)
  334. {
  335. logAi->error("Goals::VisitObj objid " + std::to_string(goal.objid) + " no longer visible, probably goal used for something it's not intended");
  336. return -100; // FIXME: Added check when goal was used for hero instead of VisitHero, but crashes are bad anyway
  337. }
  338. std::optional<int> objValueKnownByAI = MapObjectsEvaluator::getInstance().getObjectValue(obj);
  339. int objValue = 0;
  340. if(objValueKnownByAI != std::nullopt) //consider adding value manipulation based on object instances on map
  341. {
  342. objValue = std::min(std::max(objValueKnownByAI.value(), 0), 20000);
  343. }
  344. else
  345. {
  346. MapObjectsEvaluator::getInstance().addObjectData(obj->ID, obj->subID, 0);
  347. logGlobal->error("AI met object type it doesn't know - ID: %d, subID: %d - adding to database with value %d ", obj->ID, obj->subID, objValue);
  348. }
  349. setSharedFuzzyVariables(goal);
  350. float output = -1.0f;
  351. try
  352. {
  353. objectValue->setValue(objValue);
  354. engine.process();
  355. output = static_cast<float>(value->getValue());
  356. }
  357. catch(fl::Exception & fe)
  358. {
  359. logAi->error("evaluate getWanderTargetObjectValue: %s", fe.getWhat());
  360. }
  361. assert(output >= 0.0f);
  362. return output;
  363. }
  364. VisitTileEngine::VisitTileEngine() //so far no VisitTile-specific variables that are not shared with HeroMovementGoalEngineBase
  365. {
  366. configure();
  367. }
  368. float VisitTileEngine::evaluate(Goals::VisitTile & goal)
  369. {
  370. //we assume that hero is already set and we want to choose most suitable one for the mission
  371. if(!goal.hero)
  372. return 0;
  373. //assert(cb->isInTheMap(g.tile));
  374. setSharedFuzzyVariables(goal);
  375. try
  376. {
  377. engine.process();
  378. goal.priority = static_cast<float>(value->getValue());
  379. }
  380. catch(fl::Exception & fe)
  381. {
  382. logAi->error("evaluate VisitTile: %s", fe.getWhat());
  383. }
  384. assert(goal.priority >= 0);
  385. return goal.priority;
  386. }