FuzzyHelper.cpp 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. /*
  2. * FuzzyHelper.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 "FuzzyHelper.h"
  12. #include "../../lib/mapObjects/CommonConstructors.h"
  13. #include "Goals/Goals.h"
  14. #include "VCAI.h"
  15. FuzzyHelper * fh;
  16. extern boost::thread_specific_ptr<VCAI> ai;
  17. extern boost::thread_specific_ptr<CCallback> cb;
  18. Goals::TSubgoal FuzzyHelper::chooseSolution(Goals::TGoalVec vec)
  19. {
  20. if(vec.empty())
  21. {
  22. logAi->debug("FuzzyHelper found no goals. Returning Goals::Invalid.");
  23. //no possibilities found
  24. return sptr(Goals::Invalid());
  25. }
  26. //a trick to switch between heroes less often - calculatePaths is costly
  27. auto sortByHeroes = [](const Goals::TSubgoal & lhs, const Goals::TSubgoal & rhs) -> bool
  28. {
  29. return lhs->hero.h < rhs->hero.h;
  30. };
  31. boost::sort(vec, sortByHeroes);
  32. for(auto g : vec)
  33. {
  34. setPriority(g);
  35. }
  36. auto compareGoals = [](const Goals::TSubgoal & lhs, const Goals::TSubgoal & rhs) -> bool
  37. {
  38. return lhs->priority < rhs->priority;
  39. };
  40. for(auto goal : vec)
  41. {
  42. logAi->trace("FuzzyHelper evaluated goal %s, priority=%.4f", goal->name(), goal->priority);
  43. }
  44. Goals::TSubgoal result = *boost::max_element(vec, compareGoals);
  45. logAi->debug("FuzzyHelper returned goal %s, priority=%.4f", result->name(), result->priority);
  46. return result;
  47. }
  48. ui64 FuzzyHelper::estimateBankDanger(const CBank * bank)
  49. {
  50. //this one is not fuzzy anymore, just calculate weighted average
  51. auto objectInfo = VLC->objtypeh->getHandlerFor(bank->ID, bank->subID)->getObjectInfo(bank->appearance);
  52. CBankInfo * bankInfo = dynamic_cast<CBankInfo *>(objectInfo.get());
  53. ui64 totalStrength = 0;
  54. ui8 totalChance = 0;
  55. for(auto config : bankInfo->getPossibleGuards())
  56. {
  57. totalStrength += config.second.totalStrength * config.first;
  58. totalChance += config.first;
  59. }
  60. return totalStrength / std::max<ui8>(totalChance, 1); //avoid division by zero
  61. }
  62. float FuzzyHelper::evaluate(Goals::VisitTile & g)
  63. {
  64. if(g.parent)
  65. {
  66. g.parent->accept(this);
  67. }
  68. return visitTileEngine.evaluate(g);
  69. }
  70. float FuzzyHelper::evaluate(Goals::BuildBoat & g)
  71. {
  72. const float buildBoatPenalty = 0.25;
  73. if(!g.parent)
  74. {
  75. return 0;
  76. }
  77. return g.parent->accept(this) - buildBoatPenalty;
  78. }
  79. float FuzzyHelper::evaluate(Goals::AdventureSpellCast & g)
  80. {
  81. if(!g.parent)
  82. {
  83. return 0;
  84. }
  85. const CSpell * spell = g.getSpell();
  86. const float spellCastPenalty = (float)g.hero->getSpellCost(spell) / g.hero->mana;
  87. return g.parent->accept(this) - spellCastPenalty;
  88. }
  89. float FuzzyHelper::evaluate(Goals::CompleteQuest & g)
  90. {
  91. // TODO: How to evaluate quest complexity?
  92. const float questPenalty = 0.2;
  93. if(!g.parent)
  94. {
  95. return 0;
  96. }
  97. return g.parent->accept(this) * questPenalty;
  98. }
  99. float FuzzyHelper::evaluate(Goals::VisitObj & g)
  100. {
  101. if(g.parent)
  102. {
  103. g.parent->accept(this);
  104. }
  105. return visitObjEngine.evaluate(g);
  106. }
  107. float FuzzyHelper::evaluate(Goals::VisitHero & g)
  108. {
  109. auto obj = ai->myCb->getObj(ObjectInstanceID(g.objid)); //we assume for now that these goals are similar
  110. if(!obj)
  111. return -100; //hero died in the meantime
  112. else
  113. {
  114. g.setpriority(Goals::VisitTile(obj->visitablePos()).sethero(g.hero).accept(this));
  115. }
  116. return g.priority;
  117. }
  118. float FuzzyHelper::evaluate(Goals::GatherArmy & g)
  119. {
  120. //the more army we need, the more important goal
  121. //the more army we lack, the less important goal
  122. float army = g.hero->getArmyStrength();
  123. float ratio = g.value / std::max(g.value - army, 2000.0f); //2000 is about the value of hero recruited from tavern
  124. return 5 * (ratio / (ratio + 2)); //so 50% army gives 2.5, asymptotic 5
  125. }
  126. float FuzzyHelper::evaluate(Goals::ClearWayTo & g)
  127. {
  128. if (!g.hero.h)
  129. return 0; //lowest priority
  130. return g.whatToDoToAchieve()->accept(this);
  131. }
  132. float FuzzyHelper::evaluate(Goals::BuildThis & g)
  133. {
  134. return g.priority; //TODO
  135. }
  136. float FuzzyHelper::evaluate(Goals::DigAtTile & g)
  137. {
  138. return 0;
  139. }
  140. float FuzzyHelper::evaluate(Goals::CollectRes & g)
  141. {
  142. return g.priority; //handled by ResourceManager
  143. }
  144. float FuzzyHelper::evaluate(Goals::Build & g)
  145. {
  146. return 0;
  147. }
  148. float FuzzyHelper::evaluate(Goals::BuyArmy & g)
  149. {
  150. return g.priority;
  151. }
  152. float FuzzyHelper::evaluate(Goals::Explore & g)
  153. {
  154. return 1;
  155. }
  156. float FuzzyHelper::evaluate(Goals::RecruitHero & g)
  157. {
  158. return 1;
  159. }
  160. float FuzzyHelper::evaluate(Goals::Invalid & g)
  161. {
  162. return -1e10;
  163. }
  164. float FuzzyHelper::evaluate(Goals::AbstractGoal & g)
  165. {
  166. logAi->warn("Cannot evaluate goal %s", g.name());
  167. return g.priority;
  168. }
  169. void FuzzyHelper::setPriority(Goals::TSubgoal & g) //calls evaluate - Visitor pattern
  170. {
  171. g->setpriority(g->accept(this)); //this enforces returned value is set
  172. }
  173. ui64 FuzzyHelper::evaluateDanger(crint3 tile, const CGHeroInstance * visitor)
  174. {
  175. return evaluateDanger(tile, visitor, ai.get());
  176. }
  177. ui64 FuzzyHelper::evaluateDanger(crint3 tile, const CGHeroInstance * visitor, const VCAI * ai)
  178. {
  179. auto cb = ai->myCb;
  180. const TerrainTile * t = cb->getTile(tile, false);
  181. if(!t) //we can know about guard but can't check its tile (the edge of fow)
  182. return 190000000; //MUCH
  183. ui64 objectDanger = 0;
  184. ui64 guardDanger = 0;
  185. auto visitableObjects = cb->getVisitableObjs(tile);
  186. // in some scenarios hero happens to be "under" the object (eg town). Then we consider ONLY the hero.
  187. if(vstd::contains_if(visitableObjects, objWithID<Obj::HERO>))
  188. {
  189. vstd::erase_if(visitableObjects, [](const CGObjectInstance * obj)
  190. {
  191. return !objWithID<Obj::HERO>(obj);
  192. });
  193. }
  194. if(const CGObjectInstance * dangerousObject = vstd::backOrNull(visitableObjects))
  195. {
  196. objectDanger = evaluateDanger(dangerousObject, ai); //unguarded objects can also be dangerous or unhandled
  197. if(objectDanger)
  198. {
  199. //TODO: don't downcast objects AI shouldn't know about!
  200. auto armedObj = dynamic_cast<const CArmedInstance *>(dangerousObject);
  201. if(armedObj)
  202. {
  203. float tacticalAdvantage = tacticalAdvantageEngine.getTacticalAdvantage(visitor, armedObj);
  204. objectDanger *= tacticalAdvantage; //this line tends to go infinite for allied towns (?)
  205. }
  206. }
  207. if(dangerousObject->ID == Obj::SUBTERRANEAN_GATE)
  208. {
  209. //check guard on the other side of the gate
  210. auto it = ai->knownSubterraneanGates.find(dangerousObject);
  211. if(it != ai->knownSubterraneanGates.end())
  212. {
  213. auto guards = cb->getGuardingCreatures(it->second->visitablePos());
  214. for(auto cre : guards)
  215. {
  216. float tacticalAdvantage = tacticalAdvantageEngine.getTacticalAdvantage(visitor, dynamic_cast<const CArmedInstance *>(cre));
  217. vstd::amax(guardDanger, evaluateDanger(cre, ai) * tacticalAdvantage);
  218. }
  219. }
  220. }
  221. }
  222. auto guards = cb->getGuardingCreatures(tile);
  223. for(auto cre : guards)
  224. {
  225. float tacticalAdvantage = tacticalAdvantageEngine.getTacticalAdvantage(visitor, dynamic_cast<const CArmedInstance *>(cre));
  226. vstd::amax(guardDanger, evaluateDanger(cre, ai) * tacticalAdvantage); //we are interested in strongest monster around
  227. }
  228. //TODO mozna odwiedzic blockvis nie ruszajac straznika
  229. return std::max(objectDanger, guardDanger);
  230. }
  231. ui64 FuzzyHelper::evaluateDanger(const CGObjectInstance * obj, const VCAI * ai)
  232. {
  233. auto cb = ai->myCb;
  234. if(obj->tempOwner < PlayerColor::PLAYER_LIMIT && cb->getPlayerRelations(obj->tempOwner, ai->playerID) != PlayerRelations::ENEMIES) //owned or allied objects don't pose any threat
  235. return 0;
  236. switch(obj->ID)
  237. {
  238. case Obj::TOWN:
  239. {
  240. const CGTownInstance * cre = dynamic_cast<const CGTownInstance *>(obj);
  241. return cre->getUpperArmy()->getArmyStrength();
  242. }
  243. case Obj::MONSTER:
  244. case Obj::HERO:
  245. case Obj::GARRISON:
  246. case Obj::GARRISON2:
  247. case Obj::CREATURE_GENERATOR1:
  248. case Obj::CREATURE_GENERATOR4:
  249. case Obj::MINE:
  250. case Obj::ABANDONED_MINE:
  251. {
  252. const CArmedInstance * a = dynamic_cast<const CArmedInstance *>(obj);
  253. return a->getArmyStrength();
  254. }
  255. case Obj::CRYPT: //crypt
  256. case Obj::CREATURE_BANK: //crebank
  257. case Obj::DRAGON_UTOPIA:
  258. case Obj::SHIPWRECK: //shipwreck
  259. case Obj::DERELICT_SHIP: //derelict ship
  260. // case Obj::PYRAMID:
  261. return estimateBankDanger(dynamic_cast<const CBank *>(obj));
  262. case Obj::PYRAMID:
  263. {
  264. if(obj->subID == 0)
  265. return estimateBankDanger(dynamic_cast<const CBank *>(obj));
  266. else
  267. return 0;
  268. }
  269. default:
  270. return 0;
  271. }
  272. }