FuzzyEngines.cpp 14 KB

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