Fuzzy.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. #include "StdInc.h"
  2. #include "Fuzzy.h"
  3. #include <limits>
  4. #include "../../lib/CObjectHandler.h"
  5. #include "../../lib/CCreatureHandler.h"
  6. #include "../../lib/VCMI_Lib.h"
  7. #include "../../CCallback.h"
  8. //#include "Goals.cpp"
  9. #include "VCAI.h"
  10. /*
  11. * Fuzzy.cpp, part of VCMI engine
  12. *
  13. * Authors: listed in file AUTHORS in main folder
  14. *
  15. * License: GNU General Public License v2.0 or later
  16. * Full text of license available in license.txt file, in main folder
  17. *
  18. */
  19. #define MIN_AI_STRENGHT (0.5f) //lower when combat AI gets smarter
  20. struct BankConfig;
  21. class FuzzyEngine;
  22. class InputLVar;
  23. class CGTownInstance;
  24. using namespace boost::assign;
  25. using namespace vstd;
  26. //using namespace Goals;
  27. FuzzyHelper *fh;
  28. extern boost::thread_specific_ptr<CCallback> cb;
  29. extern boost::thread_specific_ptr<VCAI> ai;
  30. struct armyStructure
  31. {
  32. float walkers, shooters, flyers;
  33. ui32 maxSpeed;
  34. };
  35. ui64 evaluateBankConfig (BankConfig * bc)
  36. {
  37. ui64 danger = 0;
  38. for (auto opt : bc->guards)
  39. {
  40. danger += VLC->creh->creatures[opt.first]->fightValue * opt.second;
  41. }
  42. return danger;
  43. }
  44. armyStructure evaluateArmyStructure (const CArmedInstance * army)
  45. {
  46. ui64 totalStrenght = army->getArmyStrength();
  47. double walkersStrenght = 0;
  48. double flyersStrenght = 0;
  49. double shootersStrenght = 0;
  50. ui32 maxSpeed = 0;
  51. for(auto s : army->Slots())
  52. {
  53. bool walker = true;
  54. if (s.second->type->hasBonusOfType(Bonus::SHOOTER))
  55. {
  56. shootersStrenght += s.second->getPower();
  57. walker = false;
  58. }
  59. if (s.second->type->hasBonusOfType(Bonus::FLYING))
  60. {
  61. flyersStrenght += s.second->getPower();
  62. walker = false;
  63. }
  64. if (walker)
  65. walkersStrenght += s.second->getPower();
  66. amax (maxSpeed, s.second->type->valOfBonuses(Bonus::STACKS_SPEED));
  67. }
  68. armyStructure as;
  69. as.walkers = walkersStrenght / totalStrenght;
  70. as.shooters = shootersStrenght / totalStrenght;
  71. as.flyers = flyersStrenght / totalStrenght;
  72. as.maxSpeed = maxSpeed;
  73. return as;
  74. }
  75. FuzzyHelper::FuzzyHelper()
  76. {
  77. engine.hedgeSet().add(new fl::HedgeSomewhat());
  78. engine.hedgeSet().add(new fl::HedgeVery());
  79. initBank();
  80. initTacticalAdvantage();
  81. initVisitTile();
  82. logAi->infoStream() << engine.toString();
  83. }
  84. void FuzzyHelper::initBank()
  85. {
  86. try
  87. {
  88. //Trivial bank estimation
  89. bankInput = new fl::InputLVar("BankInput");
  90. bankDanger = new fl::OutputLVar("BankDanger");
  91. bankInput->addTerm(new fl::SingletonTerm ("SET", 0.5));
  92. engine.addInputLVar (bankInput);
  93. engine.addOutputLVar (bankDanger);
  94. engine.addRuleBlock (&bankBlock);
  95. for (int i = 0; i < 4; ++i)
  96. {
  97. bankDanger->addTerm(new fl::TriangularTerm ("Bank" + boost::lexical_cast<std::string>(i), 0, 1));
  98. bankBlock.addRule(new fl::MamdaniRule("if BankInput is SET then BankDanger is Bank" + boost::lexical_cast<std::string>(i), engine));
  99. }
  100. }
  101. catch (fl::FuzzyException & fe)
  102. {
  103. logAi->errorStream() << "initBank " << fe.name() << ": " << fe.message();
  104. }
  105. }
  106. void FuzzyHelper::initTacticalAdvantage()
  107. {
  108. try
  109. {
  110. //Tactical advantage calculation
  111. std::vector<fl::InputLVar*> helper;
  112. ta.ourShooters = new fl::InputLVar("OurShooters");
  113. ta.ourWalkers = new fl::InputLVar("OurWalkers");
  114. ta.ourFlyers = new fl::InputLVar("OurFlyers");
  115. ta.enemyShooters = new fl::InputLVar("EnemyShooters");
  116. ta.enemyWalkers = new fl::InputLVar("EnemyWalkers");
  117. ta.enemyFlyers = new fl::InputLVar("EnemyFlyers");
  118. helper += ta.ourShooters, ta.ourWalkers, ta.ourFlyers, ta.enemyShooters, ta.enemyWalkers, ta.enemyFlyers;
  119. for (auto val : helper)
  120. {
  121. engine.addInputLVar(val);
  122. val->addTerm (new fl::ShoulderTerm("FEW", 0, 0.75, true));
  123. val->addTerm (new fl::ShoulderTerm("MANY", 0.25, 1, false));
  124. }
  125. helper.clear();
  126. ta.ourSpeed = new fl::InputLVar("OurSpeed");
  127. ta.enemySpeed = new fl::InputLVar("EnemySpeed");
  128. helper += ta.ourSpeed, ta.enemySpeed;
  129. for (auto val : helper)
  130. {
  131. engine.addInputLVar(val);
  132. val->addTerm (new fl::ShoulderTerm("LOW", 3, 6.5, true));
  133. val->addTerm (new fl::TriangularTerm("MEDIUM", 5.5, 10.5));
  134. val->addTerm (new fl::ShoulderTerm("HIGH", 8.5, 16, false));
  135. }
  136. ta.castleWalls = new fl::InputLVar("CastleWalls");
  137. engine.addInputLVar(ta.castleWalls);
  138. ta.castleWalls->addTerm(new fl::SingletonTerm("NONE", CGTownInstance::NONE));
  139. ta.castleWalls->addTerm(new fl::TrapezoidalTerm("MEDIUM", CGTownInstance::FORT, 2.5));
  140. ta.castleWalls->addTerm(new fl::ShoulderTerm("HIGH", CGTownInstance::CITADEL - 0.1, CGTownInstance::CASTLE, false));
  141. ta.bankPresent = new fl::InputLVar("Bank");
  142. engine.addInputLVar(ta.bankPresent);
  143. ta.bankPresent->addTerm(new fl::SingletonTerm("FALSE", 0));
  144. ta.bankPresent->addTerm(new fl::SingletonTerm("TRUE", 1));
  145. ta.threat = new fl::OutputLVar("Threat");
  146. engine.addOutputLVar(ta.threat);
  147. ta.threat->addTerm (new fl::ShoulderTerm("LOW", MIN_AI_STRENGHT, 1, true));
  148. ta.threat->addTerm (new fl::TriangularTerm("MEDIUM", 0.8, 1.2));
  149. ta.threat->addTerm (new fl::ShoulderTerm("HIGH", 1, 1.5, false));
  150. engine.addRuleBlock (&ta.tacticalAdvantage);
  151. ta.tacticalAdvantage.addRule(new fl::MamdaniRule("if OurShooters is MANY and EnemySpeed is LOW then Threat is very LOW", engine));
  152. ta.tacticalAdvantage.addRule(new fl::MamdaniRule("if OurSpeed is LOW and OurShooters is FEW and EnemyShooters is MANY then Threat is very HIGH", engine));
  153. ta.tacticalAdvantage.addRule(new fl::MamdaniRule("if (OurShooters is MANY and OurFlyers is MANY) and EnemyShooters is MANY then Threat is LOW", engine));
  154. ta.tacticalAdvantage.addRule(new fl::MamdaniRule("if OurShooters is MANY and EnemySpeed is HIGH then Threat is somewhat HIGH", engine));
  155. //just to cover all cases
  156. ta.tacticalAdvantage.addRule(new fl::MamdaniRule("if EnemySpeed is MEDIUM then Threat is MEDIUM", engine));
  157. ta.tacticalAdvantage.addRule(new fl::MamdaniRule("if EnemySpeed is LOW and OurShooters is FEW then Threat is MEDIUM", engine));
  158. ta.tacticalAdvantage.addRule(new fl::MamdaniRule("if Bank is TRUE and OurShooters is MANY then Threat is somewhat HIGH", engine));
  159. ta.tacticalAdvantage.addRule(new fl::MamdaniRule("if Bank is TRUE and EnemyShooters is MANY then Threat is LOW", engine));
  160. ta.tacticalAdvantage.addRule(new fl::MamdaniRule("if CastleWalls is HIGH and OurWalkers is MANY then Threat is very HIGH", engine));
  161. ta.tacticalAdvantage.addRule(new fl::MamdaniRule("if CastleWalls is HIGH and OurFlyers is MANY and OurShooters is MANY then Threat is MEDIUM", engine));
  162. ta.tacticalAdvantage.addRule(new fl::MamdaniRule("if CastleWalls is MEDIUM and OurShooters is MANY and EnemyWalkers is MANY then Threat is LOW", engine));
  163. }
  164. catch(fl::ParsingException & pe)
  165. {
  166. logAi->errorStream() << "initTacticalAdvantage " << pe.name() << ": " << pe.message();
  167. }
  168. catch (fl::FuzzyException & fe)
  169. {
  170. logAi->errorStream() << "initTacticalAdvantage " << fe.name() << ": " << fe.message();
  171. }
  172. }
  173. ui64 FuzzyHelper::estimateBankDanger (int ID)
  174. {
  175. std::vector <ConstTransitivePtr<BankConfig>> & configs = VLC->objh->banksInfo[ID];
  176. ui64 val = std::numeric_limits<ui64>::max();
  177. try
  178. {
  179. switch (configs.size())
  180. {
  181. case 4:
  182. try
  183. {
  184. for (int i = 0; i < 4; ++i)
  185. {
  186. int bankVal = evaluateBankConfig (VLC->objh->banksInfo[ID][i]);
  187. bankDanger->term("Bank" + boost::lexical_cast<std::string>(i))->setMinimum(bankVal * 0.5f);
  188. bankDanger->term("Bank" + boost::lexical_cast<std::string>(i))->setMaximum(bankVal * 1.5f);
  189. }
  190. //comparison purposes
  191. //int averageValue = (evaluateBankConfig (VLC->objh->banksInfo[ID][0]) + evaluateBankConfig (VLC->objh->banksInfo[ID][3])) * 0.5;
  192. //dynamic_cast<fl::SingletonTerm*>(bankInput->term("SET"))->setValue(0.5);
  193. bankInput->setInput (0.5);
  194. engine.process (BANK_DANGER);
  195. //engine.process();
  196. val = bankDanger->output().defuzzify(); //some expected value of this bank
  197. }
  198. catch (fl::FuzzyException & fe)
  199. {
  200. logAi->errorStream() << fe.name() << ": " << fe.message();
  201. }
  202. break;
  203. case 1: //rare case - Pyramid
  204. val = evaluateBankConfig (VLC->objh->banksInfo[ID][0]);
  205. break;
  206. default:
  207. logAi->warnStream() << ("Uhnandled bank config!");
  208. }
  209. }
  210. catch (fl::FuzzyException & fe)
  211. {
  212. logAi->errorStream() << "estimateBankDanger " << fe.name() << ": " << fe.message();
  213. }
  214. return val;
  215. }
  216. float FuzzyHelper::getTacticalAdvantage (const CArmedInstance *we, const CArmedInstance *enemy)
  217. {
  218. float output = 1;
  219. try
  220. {
  221. armyStructure ourStructure = evaluateArmyStructure(we);
  222. armyStructure enemyStructure = evaluateArmyStructure(enemy);
  223. ta.ourWalkers->setInput(ourStructure.walkers);
  224. ta.ourShooters->setInput(ourStructure.shooters);
  225. ta.ourFlyers->setInput(ourStructure.flyers);
  226. ta.ourSpeed->setInput(ourStructure.maxSpeed);
  227. ta.enemyWalkers->setInput(enemyStructure.walkers);
  228. ta.enemyShooters->setInput(enemyStructure.shooters);
  229. ta.enemyFlyers->setInput(enemyStructure.flyers);
  230. ta.enemySpeed->setInput(enemyStructure.maxSpeed);
  231. bool bank = dynamic_cast<const CBank*>(enemy);
  232. if (bank)
  233. ta.bankPresent->setInput(1);
  234. else
  235. ta.bankPresent->setInput(0);
  236. const CGTownInstance * fort = dynamic_cast<const CGTownInstance*>(enemy);
  237. if (fort)
  238. {
  239. ta.castleWalls->setInput (fort->fortLevel());
  240. }
  241. else
  242. ta.castleWalls->setInput(0);
  243. engine.process (TACTICAL_ADVANTAGE);
  244. //engine.process();
  245. output = ta.threat->output().defuzzify();
  246. }
  247. catch (fl::FuzzyException & fe)
  248. {
  249. logAi->errorStream() << "getTacticalAdvantage " << fe.name() << ": " << fe.message();
  250. }
  251. return output;
  252. }
  253. FuzzyHelper::TacticalAdvantage::~TacticalAdvantage()
  254. {
  255. //TODO: smart pointers?
  256. delete ourWalkers;
  257. delete ourShooters;
  258. delete ourFlyers;
  259. delete enemyWalkers;
  260. delete enemyShooters;
  261. delete enemyFlyers;
  262. delete ourSpeed;
  263. delete enemySpeed;
  264. delete bankPresent;
  265. delete castleWalls;
  266. delete threat;
  267. }
  268. //shared_ptr<AbstractGoal> chooseSolution (std::vector<shared_ptr<AbstractGoal>> & vec)
  269. Goals::TSubgoal FuzzyHelper::chooseSolution (Goals::TGoalVec vec)
  270. {
  271. if (vec.empty()) //no possibilities found
  272. return sptr(Goals::Invalid());
  273. for (auto g : vec)
  274. {
  275. setPriority(g);
  276. }
  277. auto compareGoals = [](const Goals::TSubgoal & lhs, const Goals::TSubgoal & rhs) -> bool
  278. {
  279. return lhs->priority < rhs->priority;
  280. };
  281. boost::sort (vec, compareGoals);
  282. return vec.back();
  283. }
  284. float FuzzyHelper::evaluate (Goals::Explore & g)
  285. {
  286. return 1;
  287. }
  288. float FuzzyHelper::evaluate (Goals::RecruitHero & g)
  289. {
  290. return 1; //just try to recruit hero as one of options
  291. }
  292. FuzzyHelper::EvalVisitTile::~EvalVisitTile()
  293. {
  294. delete strengthRatio;
  295. delete heroStrength;
  296. delete tileDistance;
  297. delete missionImportance;
  298. delete movement;
  299. }
  300. void FuzzyHelper::initVisitTile()
  301. {
  302. try
  303. {
  304. std::vector<fl::InputLVar*> helper;
  305. vt.strengthRatio = new fl::InputLVar("strengthRatio"); //hero must be strong enough to defeat guards
  306. vt.heroStrength = new fl::InputLVar("heroStrength"); //we want to use weakest possible hero
  307. vt.tileDistance = new fl::InputLVar("tileDistance"); //we want to use hero who is near
  308. vt.missionImportance = new fl::InputLVar("lockedMissionImportance"); //we may want to preempt hero with low-priority mission
  309. vt.movement = new fl::InputLVar("movement");
  310. vt.value = new fl::OutputLVar("Value");
  311. helper += vt.strengthRatio, vt.heroStrength, vt.tileDistance, vt.missionImportance, vt.movement;
  312. for (auto val : helper)
  313. {
  314. engine.addInputLVar(val);
  315. }
  316. engine.addOutputLVar (vt.value);
  317. vt.strengthRatio->addTerm (new fl::ShoulderTerm("LOW", 0, SAFE_ATTACK_CONSTANT, true));
  318. vt.strengthRatio->addTerm (new fl::ShoulderTerm("HIGH", SAFE_ATTACK_CONSTANT, SAFE_ATTACK_CONSTANT * 5, false));
  319. //strength compared to our main hero
  320. vt.heroStrength->addTerm (new fl::ShoulderTerm("LOW", 0, 0.2, true));
  321. vt.heroStrength->addTerm (new fl::TriangularTerm("MEDIUM", 0.2, 0.8));
  322. vt.heroStrength->addTerm (new fl::ShoulderTerm("HIGH", 0.5, 0.99, false));
  323. vt.tileDistance->addTerm (new fl::ShoulderTerm("SMALL", 0, 3.5, true));
  324. vt.tileDistance->addTerm (new fl::TriangularTerm("MEDIUM", 3, 10.5));
  325. vt.tileDistance->addTerm (new fl::ShoulderTerm("LONG", 10, 50, false));
  326. vt.missionImportance->addTerm (new fl::ShoulderTerm("LOW", 0, 2.5, true));
  327. vt.missionImportance->addTerm (new fl::TriangularTerm("MEDIUM", 2, 3));
  328. vt.missionImportance->addTerm (new fl::ShoulderTerm("HIGH", 2.5, 5, false));
  329. vt.movement->addTerm (new fl::ShoulderTerm("LOW", 0, 600, true));
  330. vt.movement->addTerm (new fl::TriangularTerm("MEDIUM", 500, 1500));
  331. vt.movement->addTerm (new fl::ShoulderTerm("HIGH", 1000, 2000, false));
  332. vt.value->addTerm (new fl::ShoulderTerm("LOW", 0, 2.5, true)); //should be same as "mission Importance" to keep consistency
  333. vt.value->addTerm (new fl::TriangularTerm("MEDIUM", 2, 3));
  334. vt.value->addTerm (new fl::ShoulderTerm("HIGH", 2.5, 5, false));
  335. engine.addRuleBlock (&vt.rules);
  336. //use unarmed scouts if possible
  337. vt.rules.addRule (new fl::MamdaniRule("if strengthRatio is HIGH and heroStrength is LOW then Value is very HIGH", engine));
  338. //we may want to use secondary hero(es) rather than main hero
  339. vt.rules.addRule (new fl::MamdaniRule("if strengthRatio is HIGH and heroStrength is MEDIUM then Value is somewhat HIGH", engine));
  340. vt.rules.addRule (new fl::MamdaniRule("if strengthRatio is HIGH and heroStrength is HIGH then Value is somewhat LOW", engine));
  341. //don't assign targets to heroes who are too weak, but prefer targets of our main hero (in case we need to gather army)
  342. vt.rules.addRule (new fl::MamdaniRule("if strengthRatio is LOW and heroStrength is LOW then Value is very LOW", engine));
  343. vt.rules.addRule (new fl::MamdaniRule("if strengthRatio is LOW and heroStrength is HIGH then Value is LOW", engine));
  344. //do not cancel important goals
  345. vt.rules.addRule (new fl::MamdaniRule("if lockedMissionImportance is HIGH then Value is very LOW", engine));
  346. vt.rules.addRule (new fl::MamdaniRule("if lockedMissionImportance is MEDIUM then Value is somewhat LOW", engine));
  347. vt.rules.addRule (new fl::MamdaniRule("if lockedMissionImportance is LOW then Value is HIGH", engine));
  348. //pick nearby objects if it's easy, avoid long walks
  349. vt.rules.addRule (new fl::MamdaniRule("if tileDistance is SMALL then Value is HIGH", engine));
  350. vt.rules.addRule (new fl::MamdaniRule("if tileDistance is MEDIUM then Value is MEDIUM", engine));
  351. vt.rules.addRule (new fl::MamdaniRule("if tileDistance is LONG then Value is LOW", engine));
  352. //use heroes with movement points first
  353. vt.rules.addRule (new fl::MamdaniRule("if movement is LOW then Value is somewhat LOW", engine));
  354. vt.rules.addRule (new fl::MamdaniRule("if movement is MEDIUM then Value is MEDIUM", engine));
  355. vt.rules.addRule (new fl::MamdaniRule("if movement is HIGH then Value is somewhat HIGH", engine));
  356. }
  357. catch (fl::FuzzyException & fe)
  358. {
  359. logAi->errorStream() << "visitTile " << fe.name() << ": " << fe.message();
  360. }
  361. }
  362. float FuzzyHelper::evaluate (Goals::VisitTile & g)
  363. {
  364. //we assume that hero is already set and we want to choose most suitable one for the mission
  365. if (!g.hero)
  366. return 0;
  367. cb->setSelection (g.hero.h);
  368. int distance = cb->getDistance(g.tile); //at this point we already assume tile is reachable
  369. float missionImportance = 0;
  370. if (vstd::contains(ai->lockedHeroes, g.hero))
  371. missionImportance = ai->lockedHeroes[g.hero]->priority;
  372. float strengthRatio = 100; //we are much stronger than enemy
  373. ui64 danger = evaluateDanger (g.tile, g.hero.h);
  374. if (danger)
  375. strengthRatio = (fl::flScalar)g.hero.h->getTotalStrength() / danger;
  376. try
  377. {
  378. vt.strengthRatio->setInput (strengthRatio);
  379. vt.heroStrength->setInput ((fl::flScalar)g.hero->getTotalStrength()/ai->primaryHero()->getTotalStrength());
  380. vt.tileDistance->setInput (distance);
  381. vt.missionImportance->setInput (missionImportance);
  382. vt.movement->setInput(g.hero->movement);
  383. //engine.process();
  384. engine.process (VISIT_TILE);
  385. g.priority = vt.value->output().defuzzify();
  386. }
  387. catch (fl::FuzzyException & fe)
  388. {
  389. logAi->errorStream() << "evaluate VisitTile " << fe.name() << ": " << fe.message();
  390. }
  391. return g.priority;
  392. }
  393. float FuzzyHelper::evaluate (Goals::VisitHero & g)
  394. {
  395. auto obj = cb->getObj(ObjectInstanceID(g.objid)); //we assume for now that these goals are similiar
  396. //TODO: consider direct copy (constructor?)
  397. g.setpriority(Goals::VisitTile(obj->visitablePos()).sethero(g.hero).setisAbstract(g.isAbstract).accept(this));
  398. return g.priority;
  399. }
  400. float FuzzyHelper::evaluate (Goals::BuildThis & g)
  401. {
  402. return 1;
  403. }
  404. float FuzzyHelper::evaluate (Goals::DigAtTile & g)
  405. {
  406. return 0;
  407. }
  408. float FuzzyHelper::evaluate (Goals::CollectRes & g)
  409. {
  410. return 0;
  411. }
  412. float FuzzyHelper::evaluate (Goals::Build & g)
  413. {
  414. return 0;
  415. }
  416. float FuzzyHelper::evaluate (Goals::Invalid & g)
  417. {
  418. return -1e10;
  419. }
  420. float FuzzyHelper::evaluate (Goals::AbstractGoal & g)
  421. {
  422. logAi->warnStream() << boost::format("Cannot evaluate goal %s") % g.name();
  423. return g.priority;
  424. }
  425. void FuzzyHelper::setPriority (Goals::TSubgoal & g)
  426. {
  427. g->setpriority(g->accept(this)); //this enforces returned value is set
  428. }