FuzzyHelper.cpp 8.6 KB

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