FuzzyEngines.cpp 15 KB

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