Fuzzy.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. #include "StdInc.h"
  2. #include "Fuzzy.h"
  3. #include <limits>
  4. #include "../../lib/mapObjects/MapObjects.h"
  5. #include "../../lib/mapObjects/CommonConstructors.h"
  6. #include "../../lib/CCreatureHandler.h"
  7. #include "../../lib/CPathfinder.h"
  8. #include "../../lib/CGameStateFwd.h"
  9. #include "../../lib/VCMI_Lib.h"
  10. #include "../../CCallback.h"
  11. #include "VCAI.h"
  12. /*
  13. * Fuzzy.cpp, part of VCMI engine
  14. *
  15. * Authors: listed in file AUTHORS in main folder
  16. *
  17. * License: GNU General Public License v2.0 or later
  18. * Full text of license available in license.txt file, in main folder
  19. *
  20. */
  21. #define MIN_AI_STRENGHT (0.5f) //lower when combat AI gets smarter
  22. #define UNGUARDED_OBJECT (100.0f) //we consider unguarded objects 100 times weaker than us
  23. struct BankConfig;
  24. class IObjectInfo;
  25. class CBankInfo;
  26. class Engine;
  27. class InputVariable;
  28. class CGTownInstance;
  29. //using namespace Goals;
  30. FuzzyHelper *fh;
  31. extern boost::thread_specific_ptr<CCallback> cb;
  32. extern boost::thread_specific_ptr<VCAI> ai;
  33. engineBase::engineBase()
  34. {
  35. engine.addRuleBlock(&rules);
  36. }
  37. void engineBase::configure()
  38. {
  39. engine.configure("Minimum", "Maximum", "Minimum", "AlgebraicSum", "Centroid");
  40. logAi->info(engine.toString());
  41. }
  42. void engineBase::addRule(const std::string &txt)
  43. {
  44. rules.addRule(fl::Rule::parse(txt, &engine));
  45. }
  46. struct armyStructure
  47. {
  48. float walkers, shooters, flyers;
  49. ui32 maxSpeed;
  50. };
  51. armyStructure evaluateArmyStructure (const CArmedInstance * army)
  52. {
  53. ui64 totalStrenght = army->getArmyStrength();
  54. double walkersStrenght = 0;
  55. double flyersStrenght = 0;
  56. double shootersStrenght = 0;
  57. ui32 maxSpeed = 0;
  58. for(auto s : army->Slots())
  59. {
  60. bool walker = true;
  61. if (s.second->type->hasBonusOfType(Bonus::SHOOTER))
  62. {
  63. shootersStrenght += s.second->getPower();
  64. walker = false;
  65. }
  66. if (s.second->type->hasBonusOfType(Bonus::FLYING))
  67. {
  68. flyersStrenght += s.second->getPower();
  69. walker = false;
  70. }
  71. if (walker)
  72. walkersStrenght += s.second->getPower();
  73. vstd::amax(maxSpeed, s.second->type->valOfBonuses(Bonus::STACKS_SPEED));
  74. }
  75. armyStructure as;
  76. as.walkers = walkersStrenght / totalStrenght;
  77. as.shooters = shootersStrenght / totalStrenght;
  78. as.flyers = flyersStrenght / totalStrenght;
  79. as.maxSpeed = maxSpeed;
  80. assert(as.walkers || as.flyers || as.shooters);
  81. return as;
  82. }
  83. FuzzyHelper::FuzzyHelper()
  84. {
  85. initTacticalAdvantage();
  86. ta.configure();
  87. initVisitTile();
  88. vt.configure();
  89. }
  90. void FuzzyHelper::initTacticalAdvantage()
  91. {
  92. try
  93. {
  94. ta.ourShooters = new fl::InputVariable("OurShooters");
  95. ta.ourWalkers = new fl::InputVariable("OurWalkers");
  96. ta.ourFlyers = new fl::InputVariable("OurFlyers");
  97. ta.enemyShooters = new fl::InputVariable("EnemyShooters");
  98. ta.enemyWalkers = new fl::InputVariable("EnemyWalkers");
  99. ta.enemyFlyers = new fl::InputVariable("EnemyFlyers");
  100. //Tactical advantage calculation
  101. std::vector<fl::InputVariable*> helper =
  102. {
  103. ta.ourShooters, ta.ourWalkers, ta.ourFlyers, ta.enemyShooters, ta.enemyWalkers, ta.enemyFlyers
  104. };
  105. for (auto val : helper)
  106. {
  107. ta.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. ta.ourSpeed = new fl::InputVariable("OurSpeed");
  113. ta.enemySpeed = new fl::InputVariable("EnemySpeed");
  114. helper = {ta.ourSpeed, ta.enemySpeed};
  115. for (auto val : helper)
  116. {
  117. ta.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. ta.castleWalls = new fl::InputVariable("CastleWalls");
  124. ta.engine.addInputVariable(ta.castleWalls);
  125. {
  126. fl::Rectangle* none = new fl::Rectangle("NONE", CGTownInstance::NONE, CGTownInstance::NONE + (CGTownInstance::FORT - CGTownInstance::NONE) * 0.5f);
  127. ta.castleWalls->addTerm(none);
  128. fl::Trapezoid* medium = new fl::Trapezoid("MEDIUM", (CGTownInstance::FORT - CGTownInstance::NONE) * 0.5f, CGTownInstance::FORT,
  129. CGTownInstance::CITADEL, CGTownInstance::CITADEL + (CGTownInstance::CASTLE - CGTownInstance::CITADEL) * 0.5f);
  130. ta.castleWalls->addTerm(medium);
  131. fl::Ramp* high = new fl::Ramp("HIGH", CGTownInstance::CITADEL - 0.1, CGTownInstance::CASTLE);
  132. ta.castleWalls->addTerm(high);
  133. ta.castleWalls->setRange(CGTownInstance::NONE, CGTownInstance::CASTLE);
  134. }
  135. ta.bankPresent = new fl::InputVariable("Bank");
  136. ta.engine.addInputVariable(ta.bankPresent);
  137. {
  138. fl::Rectangle* termFalse = new fl::Rectangle("FALSE", 0.0, 0.5f);
  139. ta.bankPresent->addTerm(termFalse);
  140. fl::Rectangle* termTrue = new fl::Rectangle("TRUE", 0.5f, 1);
  141. ta.bankPresent->addTerm(termTrue);
  142. ta.bankPresent->setRange(0, 1);
  143. }
  144. ta.threat = new fl::OutputVariable("Threat");
  145. ta.engine.addOutputVariable(ta.threat);
  146. ta.threat->addTerm(new fl::Ramp("LOW", 1, MIN_AI_STRENGHT));
  147. ta.threat->addTerm(new fl::Triangle("MEDIUM", 0.8, 1.2));
  148. ta.threat->addTerm(new fl::Ramp("HIGH", 1, 1.5));
  149. ta.threat->setRange(MIN_AI_STRENGHT, 1.5);
  150. ta.addRule("if OurShooters is MANY and EnemySpeed is LOW then Threat is LOW");
  151. ta.addRule("if OurShooters is MANY and EnemyShooters is FEW then Threat is LOW");
  152. ta.addRule("if OurSpeed is LOW and EnemyShooters is MANY then Threat is HIGH");
  153. ta.addRule("if OurSpeed is HIGH and EnemyShooters is MANY then Threat is LOW");
  154. ta.addRule("if OurWalkers is FEW and EnemyShooters is MANY then Threat is somewhat LOW");
  155. ta.addRule("if OurShooters is MANY and EnemySpeed is HIGH then Threat is somewhat HIGH");
  156. //just to cover all cases
  157. ta.addRule("if OurShooters is FEW and EnemySpeed is HIGH then Threat is MEDIUM");
  158. ta.addRule("if EnemySpeed is MEDIUM then Threat is MEDIUM");
  159. ta.addRule("if EnemySpeed is LOW and OurShooters is FEW then Threat is MEDIUM");
  160. ta.addRule("if Bank is TRUE and OurShooters is MANY then Threat is somewhat HIGH");
  161. ta.addRule("if Bank is TRUE and EnemyShooters is MANY then Threat is LOW");
  162. ta.addRule("if CastleWalls is HIGH and OurWalkers is MANY then Threat is very HIGH");
  163. ta.addRule("if CastleWalls is HIGH and OurFlyers is MANY and OurShooters is MANY then Threat is MEDIUM");
  164. ta.addRule("if CastleWalls is MEDIUM and OurShooters is MANY and EnemyWalkers is MANY then Threat is LOW");
  165. }
  166. catch (fl::Exception & pe)
  167. {
  168. logAi->error("initTacticalAdvantage: %s", pe.getWhat());
  169. }
  170. }
  171. ui64 FuzzyHelper::estimateBankDanger (const CBank * bank)
  172. {
  173. //this one is not fuzzy anymore, just calculate weighted average
  174. auto objectInfo = VLC->objtypeh->getHandlerFor(bank->ID, bank->subID)->getObjectInfo(bank->appearance);
  175. CBankInfo * bankInfo = dynamic_cast<CBankInfo *> (objectInfo.get());
  176. ui64 totalStrength = 0;
  177. ui8 totalChance = 0;
  178. for (auto config : bankInfo->getPossibleGuards())
  179. {
  180. totalStrength += config.second.totalStrength * config.first;
  181. totalChance += config.first;
  182. }
  183. return totalStrength / totalChance;
  184. }
  185. float FuzzyHelper::getTacticalAdvantage (const CArmedInstance *we, const CArmedInstance *enemy)
  186. {
  187. float output = 1;
  188. try
  189. {
  190. armyStructure ourStructure = evaluateArmyStructure(we);
  191. armyStructure enemyStructure = evaluateArmyStructure(enemy);
  192. ta.ourWalkers->setInputValue(ourStructure.walkers);
  193. ta.ourShooters->setInputValue(ourStructure.shooters);
  194. ta.ourFlyers->setInputValue(ourStructure.flyers);
  195. ta.ourSpeed->setInputValue(ourStructure.maxSpeed);
  196. ta.enemyWalkers->setInputValue(enemyStructure.walkers);
  197. ta.enemyShooters->setInputValue(enemyStructure.shooters);
  198. ta.enemyFlyers->setInputValue(enemyStructure.flyers);
  199. ta.enemySpeed->setInputValue(enemyStructure.maxSpeed);
  200. bool bank = dynamic_cast<const CBank*> (enemy);
  201. if (bank)
  202. ta.bankPresent->setInputValue(1);
  203. else
  204. ta.bankPresent->setInputValue(0);
  205. const CGTownInstance * fort = dynamic_cast<const CGTownInstance*> (enemy);
  206. if (fort)
  207. {
  208. ta.castleWalls->setInputValue(fort->fortLevel());
  209. }
  210. else
  211. ta.castleWalls->setInputValue(0);
  212. //engine.process(TACTICAL_ADVANTAGE);//TODO: Process only Tactical_Advantage
  213. ta.engine.process();
  214. output = ta.threat->getOutputValue();
  215. }
  216. catch (fl::Exception & fe)
  217. {
  218. logAi->error("getTacticalAdvantage: %s ",fe.getWhat());
  219. }
  220. if (output < 0 || (output != output))
  221. {
  222. fl::InputVariable* tab[] = {ta.bankPresent, ta.castleWalls, ta.ourWalkers, ta.ourShooters, ta.ourFlyers, ta.ourSpeed, ta.enemyWalkers, ta.enemyShooters, ta.enemyFlyers, ta.enemySpeed};
  223. std::string names[] = {"bankPresent", "castleWalls", "ourWalkers", "ourShooters", "ourFlyers", "ourSpeed", "enemyWalkers", "enemyShooters", "enemyFlyers", "enemySpeed" };
  224. std::stringstream log("Warning! Fuzzy engine doesn't cover this set of parameters: ");
  225. for (int i = 0; i < boost::size(tab); i++)
  226. log << names[i] << ": " << tab[i]->getInputValue() << " ";
  227. logAi->error(log.str());
  228. assert(false);
  229. }
  230. return output;
  231. }
  232. FuzzyHelper::TacticalAdvantage::~TacticalAdvantage()
  233. {
  234. //TODO: smart pointers?
  235. delete ourWalkers;
  236. delete ourShooters;
  237. delete ourFlyers;
  238. delete enemyWalkers;
  239. delete enemyShooters;
  240. delete enemyFlyers;
  241. delete ourSpeed;
  242. delete enemySpeed;
  243. delete bankPresent;
  244. delete castleWalls;
  245. delete threat;
  246. }
  247. //std::shared_ptr<AbstractGoal> chooseSolution (std::vector<std::shared_ptr<AbstractGoal>> & vec)
  248. Goals::TSubgoal FuzzyHelper::chooseSolution (Goals::TGoalVec vec)
  249. {
  250. if (vec.empty()) //no possibilities found
  251. return sptr(Goals::Invalid());
  252. ai->cachedSectorMaps.clear();
  253. //a trick to switch between heroes less often - calculatePaths is costly
  254. auto sortByHeroes = [](const Goals::TSubgoal & lhs, const Goals::TSubgoal & rhs) -> bool
  255. {
  256. return lhs->hero.h < rhs->hero.h;
  257. };
  258. boost::sort (vec, sortByHeroes);
  259. for (auto g : vec)
  260. {
  261. setPriority(g);
  262. }
  263. auto compareGoals = [](const Goals::TSubgoal & lhs, const Goals::TSubgoal & rhs) -> bool
  264. {
  265. return lhs->priority < rhs->priority;
  266. };
  267. boost::sort (vec, compareGoals);
  268. return vec.back();
  269. }
  270. float FuzzyHelper::evaluate (Goals::Explore & g)
  271. {
  272. return 1;
  273. }
  274. float FuzzyHelper::evaluate (Goals::RecruitHero & g)
  275. {
  276. return 1; //just try to recruit hero as one of options
  277. }
  278. FuzzyHelper::EvalVisitTile::~EvalVisitTile()
  279. {
  280. delete strengthRatio;
  281. delete heroStrength;
  282. delete turnDistance;
  283. delete missionImportance;
  284. }
  285. void FuzzyHelper::initVisitTile()
  286. {
  287. try
  288. {
  289. vt.strengthRatio = new fl::InputVariable("strengthRatio"); //hero must be strong enough to defeat guards
  290. vt.heroStrength = new fl::InputVariable("heroStrength"); //we want to use weakest possible hero
  291. vt.turnDistance = new fl::InputVariable("turnDistance"); //we want to use hero who is near
  292. vt.missionImportance = new fl::InputVariable("lockedMissionImportance"); //we may want to preempt hero with low-priority mission
  293. vt.value = new fl::OutputVariable("Value");
  294. vt.value->setMinimum(0);
  295. vt.value->setMaximum(5);
  296. std::vector<fl::InputVariable*> helper = {vt.strengthRatio, vt.heroStrength, vt.turnDistance, vt.missionImportance};
  297. for (auto val : helper)
  298. {
  299. vt.engine.addInputVariable(val);
  300. }
  301. vt.engine.addOutputVariable(vt.value);
  302. vt.strengthRatio->addTerm(new fl::Ramp("LOW", SAFE_ATTACK_CONSTANT, 0));
  303. vt.strengthRatio->addTerm(new fl::Ramp("HIGH", SAFE_ATTACK_CONSTANT, SAFE_ATTACK_CONSTANT * 3));
  304. vt.strengthRatio->setRange(0, SAFE_ATTACK_CONSTANT * 3 );
  305. //strength compared to our main hero
  306. vt.heroStrength->addTerm(new fl::Ramp("LOW", 0.2, 0));
  307. vt.heroStrength->addTerm(new fl::Triangle("MEDIUM", 0.2, 0.8));
  308. vt.heroStrength->addTerm(new fl::Ramp("HIGH", 0.5, 1));
  309. vt.heroStrength->setRange(0.0, 1.0);
  310. vt.turnDistance->addTerm(new fl::Ramp("SMALL", 0.5, 0));
  311. vt.turnDistance->addTerm(new fl::Triangle("MEDIUM", 0.1, 0.8));
  312. vt.turnDistance->addTerm(new fl::Ramp("LONG", 0.5, 3));
  313. vt.turnDistance->setRange(0.0, 3.0);
  314. vt.missionImportance->addTerm(new fl::Ramp("LOW", 2.5, 0));
  315. vt.missionImportance->addTerm(new fl::Triangle("MEDIUM", 2, 3));
  316. vt.missionImportance->addTerm(new fl::Ramp("HIGH", 2.5, 5));
  317. vt.missionImportance->setRange(0.0, 5.0);
  318. //an issue: in 99% cases this outputs center of mass (2.5) regardless of actual input :/
  319. //should be same as "mission Importance" to keep consistency
  320. vt.value->addTerm(new fl::Ramp("LOW", 2.5, 0));
  321. vt.value->addTerm(new fl::Triangle("MEDIUM", 2, 3)); //can't be center of mass :/
  322. vt.value->addTerm(new fl::Ramp("HIGH", 2.5, 5));
  323. vt.value->setRange(0.0,5.0);
  324. //use unarmed scouts if possible
  325. vt.addRule("if strengthRatio is HIGH and heroStrength is LOW then Value is very HIGH");
  326. //we may want to use secondary hero(es) rather than main hero
  327. vt.addRule("if strengthRatio is HIGH and heroStrength is MEDIUM then Value is somewhat HIGH");
  328. vt.addRule("if strengthRatio is HIGH and heroStrength is HIGH then Value is somewhat LOW");
  329. //don't assign targets to heroes who are too weak, but prefer targets of our main hero (in case we need to gather army)
  330. vt.addRule("if strengthRatio is LOW and heroStrength is LOW then Value is very LOW");
  331. //attempt to arm secondary heroes is not stupid
  332. vt.addRule("if strengthRatio is LOW and heroStrength is MEDIUM then Value is somewhat HIGH");
  333. vt.addRule("if strengthRatio is LOW and heroStrength is HIGH then Value is LOW");
  334. //do not cancel important goals
  335. vt.addRule("if lockedMissionImportance is HIGH then Value is very LOW");
  336. vt.addRule("if lockedMissionImportance is MEDIUM then Value is somewhat LOW");
  337. vt.addRule("if lockedMissionImportance is LOW then Value is HIGH");
  338. //pick nearby objects if it's easy, avoid long walks
  339. vt.addRule("if turnDistance is SMALL then Value is HIGH");
  340. vt.addRule("if turnDistance is MEDIUM then Value is MEDIUM");
  341. vt.addRule("if turnDistance is LONG then Value is LOW");
  342. }
  343. catch (fl::Exception & fe)
  344. {
  345. logAi->error("visitTile: %s",fe.getWhat());
  346. }
  347. }
  348. float FuzzyHelper::evaluate (Goals::VisitTile & g)
  349. {
  350. //we assume that hero is already set and we want to choose most suitable one for the mission
  351. if (!g.hero)
  352. return 0;
  353. //assert(cb->isInTheMap(g.tile));
  354. float turns = 0;
  355. float distance = CPathfinderHelper::getMovementCost(g.hero.h, g.tile);
  356. if (!distance) //we stand on that tile
  357. turns = 0;
  358. else
  359. {
  360. if (distance < g.hero->movement) //we can move there within one turn
  361. turns = (fl::scalar)distance / g.hero->movement;
  362. else
  363. turns = 1 + (fl::scalar)(distance - g.hero->movement) / g.hero->maxMovePoints(true); //bool on land?
  364. }
  365. float missionImportance = 0;
  366. if (vstd::contains(ai->lockedHeroes, g.hero))
  367. missionImportance = ai->lockedHeroes[g.hero]->priority;
  368. float strengthRatio = 10.0f; //we are much stronger than enemy
  369. ui64 danger = evaluateDanger (g.tile, g.hero.h);
  370. if (danger)
  371. strengthRatio = (fl::scalar)g.hero.h->getTotalStrength() / danger;
  372. try
  373. {
  374. vt.strengthRatio->setInputValue(strengthRatio);
  375. vt.heroStrength->setInputValue((fl::scalar)g.hero->getTotalStrength() / ai->primaryHero()->getTotalStrength());
  376. vt.turnDistance->setInputValue(turns);
  377. vt.missionImportance->setInputValue(missionImportance);
  378. vt.engine.process();
  379. //engine.process(VISIT_TILE); //TODO: Process only Visit_Tile
  380. g.priority = vt.value->getOutputValue();
  381. }
  382. catch (fl::Exception & fe)
  383. {
  384. logAi->error("evaluate VisitTile: %s",fe.getWhat());
  385. }
  386. assert (g.priority >= 0);
  387. return g.priority;
  388. }
  389. float FuzzyHelper::evaluate (Goals::VisitHero & g)
  390. {
  391. auto obj = cb->getObj(ObjectInstanceID(g.objid)); //we assume for now that these goals are similar
  392. if (!obj)
  393. return -100; //hero died in the meantime
  394. //TODO: consider direct copy (constructor?)
  395. g.setpriority(Goals::VisitTile(obj->visitablePos()).sethero(g.hero).setisAbstract(g.isAbstract).accept(this));
  396. return g.priority;
  397. }
  398. float FuzzyHelper::evaluate (Goals::GatherArmy & g)
  399. {
  400. //the more army we need, the more important goal
  401. //the more army we lack, the less important goal
  402. float army = g.hero->getArmyStrength();
  403. return g.value / std::max(g.value - army, 1000.0f);
  404. }
  405. float FuzzyHelper::evaluate (Goals::ClearWayTo & g)
  406. {
  407. if (!g.hero.h)
  408. throw cannotFulfillGoalException("ClearWayTo called without hero!");
  409. int3 t = ai->getCachedSectorMap(g.hero)->firstTileToGet(g.hero, g.tile);
  410. if (t.valid())
  411. {
  412. if (isSafeToVisit(g.hero, t))
  413. {
  414. g.setpriority(Goals::VisitTile(g.tile).sethero(g.hero).setisAbstract(g.isAbstract).accept(this));
  415. }
  416. else
  417. {
  418. g.setpriority (Goals::GatherArmy(evaluateDanger(t, g.hero.h)*SAFE_ATTACK_CONSTANT).
  419. sethero(g.hero).setisAbstract(true).accept(this));
  420. }
  421. return g.priority;
  422. }
  423. else
  424. return -1;
  425. }
  426. float FuzzyHelper::evaluate (Goals::BuildThis & g)
  427. {
  428. return 1;
  429. }
  430. float FuzzyHelper::evaluate (Goals::DigAtTile & g)
  431. {
  432. return 0;
  433. }
  434. float FuzzyHelper::evaluate (Goals::CollectRes & g)
  435. {
  436. return 0;
  437. }
  438. float FuzzyHelper::evaluate (Goals::Build & g)
  439. {
  440. return 0;
  441. }
  442. float FuzzyHelper::evaluate (Goals::Invalid & g)
  443. {
  444. return -1e10;
  445. }
  446. float FuzzyHelper::evaluate (Goals::AbstractGoal & g)
  447. {
  448. logAi->warn("Cannot evaluate goal %s", g.name());
  449. return g.priority;
  450. }
  451. void FuzzyHelper::setPriority (Goals::TSubgoal & g)
  452. {
  453. g->setpriority(g->accept(this)); //this enforces returned value is set
  454. }