AIUtility.h 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. /*
  2. * AIUtility.h, 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. #pragma once
  11. // Check windows
  12. #if _WIN32 || _WIN64
  13. #if _WIN64
  14. #define ENVIRONMENT64
  15. #else
  16. #define ENVIRONMENT32
  17. #endif
  18. #endif
  19. // Check GCC
  20. #if __GNUC__
  21. #if __x86_64__ || __ppc64__
  22. #define ENVIRONMENT64
  23. #else
  24. #define ENVIRONMENT32
  25. #endif
  26. #endif
  27. /*********************** TBB.h ********************/
  28. #include "tbb/blocked_range.h"
  29. #include "tbb/concurrent_hash_map.h"
  30. #include "tbb/concurrent_unordered_map.h"
  31. #include "tbb/concurrent_unordered_set.h"
  32. #include "tbb/concurrent_vector.h"
  33. #include "tbb/parallel_for.h"
  34. #include "tbb/parallel_invoke.h"
  35. /*********************** TBB.h ********************/
  36. #include "../../lib/VCMI_Lib.h"
  37. #include "../../lib/CBuildingHandler.h"
  38. #include "../../lib/CCreatureHandler.h"
  39. #include "../../lib/CTownHandler.h"
  40. #include "../../lib/spells/CSpellHandler.h"
  41. #include "../../lib/CStopWatch.h"
  42. #include "../../lib/mapObjects/CGHeroInstance.h"
  43. #include "../../CCallback.h"
  44. #include <chrono>
  45. using namespace tbb;
  46. using dwellingContent = std::pair<ui32, std::vector<CreatureID>>;
  47. namespace NKAI
  48. {
  49. struct creInfo;
  50. class AIGateway;
  51. class Nullkiller;
  52. const int GOLD_MINE_PRODUCTION = 1000;
  53. const int WOOD_ORE_MINE_PRODUCTION = 2;
  54. const int RESOURCE_MINE_PRODUCTION = 1;
  55. const int ACTUAL_RESOURCE_COUNT = 7;
  56. const int ALLOWED_ROAMING_HEROES = 8;
  57. //implementation-dependent
  58. extern const float SAFE_ATTACK_CONSTANT;
  59. extern const int GOLD_RESERVE;
  60. extern thread_local CCallback * cb;
  61. extern thread_local AIGateway * ai;
  62. enum HeroRole
  63. {
  64. SCOUT = 0,
  65. MAIN = 1
  66. };
  67. //provisional class for AI to store a reference to an owned hero object
  68. //checks if it's valid on access, should be used in place of const CGHeroInstance*
  69. struct DLL_EXPORT HeroPtr
  70. {
  71. const CGHeroInstance * h;
  72. ObjectInstanceID hid;
  73. public:
  74. std::string name;
  75. HeroPtr();
  76. HeroPtr(const CGHeroInstance * H);
  77. ~HeroPtr();
  78. operator bool() const
  79. {
  80. return validAndSet();
  81. }
  82. bool operator<(const HeroPtr & rhs) const;
  83. const CGHeroInstance * operator->() const;
  84. const CGHeroInstance * operator*() const; //not that consistent with -> but all interfaces use CGHeroInstance*, so it's convenient
  85. bool operator==(const HeroPtr & rhs) const;
  86. bool operator!=(const HeroPtr & rhs) const
  87. {
  88. return !(*this == rhs);
  89. }
  90. const CGHeroInstance * get(bool doWeExpectNull = false) const;
  91. const CGHeroInstance * get(CCallback * cb, bool doWeExpectNull = false) const;
  92. bool validAndSet() const;
  93. template<typename Handler> void serialize(Handler & h, const int version)
  94. {
  95. h & this->h;
  96. h & hid;
  97. h & name;
  98. }
  99. };
  100. enum BattleState
  101. {
  102. NO_BATTLE,
  103. UPCOMING_BATTLE,
  104. ONGOING_BATTLE,
  105. ENDING_BATTLE
  106. };
  107. // AI lives in a dangerous world. CGObjectInstances under pointer may got deleted/hidden.
  108. // This class stores object id, so we can detect when we lose access to the underlying object.
  109. struct ObjectIdRef
  110. {
  111. ObjectInstanceID id;
  112. const CGObjectInstance * operator->() const;
  113. operator const CGObjectInstance *() const;
  114. operator bool() const;
  115. ObjectIdRef(ObjectInstanceID _id);
  116. ObjectIdRef(const CGObjectInstance * obj);
  117. bool operator<(const ObjectIdRef & rhs) const;
  118. template<typename Handler> void serialize(Handler & h, const int version)
  119. {
  120. h & id;
  121. }
  122. };
  123. template<Obj::Type id>
  124. bool objWithID(const CGObjectInstance * obj)
  125. {
  126. return obj->ID == id;
  127. }
  128. struct creInfo
  129. {
  130. int count;
  131. CreatureID creID;
  132. const Creature * cre;
  133. int level;
  134. };
  135. creInfo infoFromDC(const dwellingContent & dc);
  136. template<class Func>
  137. void foreach_tile_pos(const Func & foo)
  138. {
  139. // some micro-optimizations since this function gets called a LOT
  140. // callback pointer is thread-specific and slow to retrieve -> read map size only once
  141. int3 mapSize = cb->getMapSize();
  142. for(int z = 0; z < mapSize.z; z++)
  143. {
  144. for(int x = 0; x < mapSize.x; x++)
  145. {
  146. for(int y = 0; y < mapSize.y; y++)
  147. {
  148. foo(int3(x, y, z));
  149. }
  150. }
  151. }
  152. }
  153. template<class Func>
  154. void foreach_tile_pos(CCallback * cbp, const Func & foo) // avoid costly retrieval of thread-specific pointer
  155. {
  156. int3 mapSize = cbp->getMapSize();
  157. for(int z = 0; z < mapSize.z; z++)
  158. {
  159. for(int x = 0; x < mapSize.x; x++)
  160. {
  161. for(int y = 0; y < mapSize.y; y++)
  162. {
  163. foo(cbp, int3(x, y, z));
  164. }
  165. }
  166. }
  167. }
  168. template<class Func>
  169. void foreach_neighbour(const int3 & pos, const Func & foo)
  170. {
  171. CCallback * cbp = cb; // avoid costly retrieval of thread-specific pointer
  172. for(const int3 & dir : int3::getDirs())
  173. {
  174. const int3 n = pos + dir;
  175. if(cbp->isInTheMap(n))
  176. foo(pos + dir);
  177. }
  178. }
  179. template<class Func>
  180. void foreach_neighbour(CCallback * cbp, const int3 & pos, const Func & foo) // avoid costly retrieval of thread-specific pointer
  181. {
  182. for(const int3 & dir : int3::getDirs())
  183. {
  184. const int3 n = pos + dir;
  185. if(cbp->isInTheMap(n))
  186. foo(cbp, pos + dir);
  187. }
  188. }
  189. bool canBeEmbarkmentPoint(const TerrainTile * t, bool fromWater);
  190. bool isObjectPassable(const CGObjectInstance * obj);
  191. bool isObjectPassable(const Nullkiller * ai, const CGObjectInstance * obj);
  192. bool isObjectPassable(const CGObjectInstance * obj, PlayerColor playerColor, PlayerRelations objectRelations);
  193. bool isBlockVisitObj(const int3 & pos);
  194. bool isWeeklyRevisitable(const CGObjectInstance * obj);
  195. bool isObjectRemovable(const CGObjectInstance * obj); //FIXME FIXME: move logic to object property!
  196. bool isSafeToVisit(HeroPtr h, uint64_t dangerStrength);
  197. bool isSafeToVisit(HeroPtr h, const CCreatureSet *, uint64_t dangerStrength);
  198. bool compareHeroStrength(HeroPtr h1, HeroPtr h2);
  199. bool compareArmyStrength(const CArmedInstance * a1, const CArmedInstance * a2);
  200. bool compareArtifacts(const CArtifactInstance * a1, const CArtifactInstance * a2);
  201. bool townHasFreeTavern(const CGTownInstance * town);
  202. uint64_t timeElapsed(std::chrono::time_point<std::chrono::high_resolution_clock> start);
  203. // todo: move to obj manager
  204. bool shouldVisit(const Nullkiller * ai, const CGHeroInstance * h, const CGObjectInstance * obj);
  205. template<typename TFunc>
  206. void pforeachTilePos(const int3 & mapSize, TFunc fn)
  207. {
  208. for(int z = 0; z < mapSize.z; ++z)
  209. {
  210. parallel_for(blocked_range<size_t>(0, mapSize.x), [&](const blocked_range<size_t>& r)
  211. {
  212. int3 pos(0, 0, z);
  213. for(pos.x = r.begin(); pos.x != r.end(); ++pos.x)
  214. {
  215. for(pos.y = 0; pos.y < mapSize.y; ++pos.y)
  216. {
  217. fn(pos);
  218. }
  219. }
  220. });
  221. }
  222. }
  223. class CDistanceSorter
  224. {
  225. const CGHeroInstance * hero;
  226. public:
  227. CDistanceSorter(const CGHeroInstance * hero)
  228. : hero(hero)
  229. {
  230. }
  231. bool operator()(const CGObjectInstance * lhs, const CGObjectInstance * rhs) const;
  232. };
  233. template <class T>
  234. class SharedPool
  235. {
  236. public:
  237. struct External_Deleter
  238. {
  239. explicit External_Deleter(std::weak_ptr<SharedPool<T>* > pool)
  240. : pool(pool)
  241. {
  242. }
  243. void operator()(T * ptr)
  244. {
  245. std::unique_ptr<T> uptr(ptr);
  246. if(auto pool_ptr = pool.lock())
  247. {
  248. (*pool_ptr.get())->add(std::move(uptr));
  249. }
  250. }
  251. private:
  252. std::weak_ptr<SharedPool<T>* > pool;
  253. };
  254. public:
  255. using ptr_type = std::unique_ptr<T, External_Deleter>;
  256. SharedPool(std::function<std::unique_ptr<T>()> elementFactory):
  257. elementFactory(elementFactory), pool(), instance_tracker(new SharedPool<T> *(this))
  258. {}
  259. void add(std::unique_ptr<T> t)
  260. {
  261. boost::lock_guard<boost::mutex> lock(sync);
  262. pool.push_back(std::move(t));
  263. }
  264. ptr_type acquire()
  265. {
  266. boost::lock_guard<boost::mutex> lock(sync);
  267. bool poolIsEmpty = pool.empty();
  268. T * element = poolIsEmpty
  269. ? elementFactory().release()
  270. : pool.back().release();
  271. ptr_type tmp(
  272. element,
  273. External_Deleter(std::weak_ptr<SharedPool<T>*>(instance_tracker)));
  274. if(!poolIsEmpty) pool.pop_back();
  275. return tmp;
  276. }
  277. bool empty() const
  278. {
  279. return pool.empty();
  280. }
  281. size_t size() const
  282. {
  283. return pool.size();
  284. }
  285. private:
  286. std::vector<std::unique_ptr<T>> pool;
  287. std::function<std::unique_ptr<T>()> elementFactory;
  288. std::shared_ptr<SharedPool<T> *> instance_tracker;
  289. boost::mutex sync;
  290. };
  291. }