FuzzyHelper.cpp 8.7 KB

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