2
0

ResourceManager.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. /*
  2. * ResourceManager.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 "ResourceManager.h"
  12. #include "../../CCallback.h"
  13. #include "../../lib/mapObjects/MapObjects.h"
  14. #define GOLD_RESERVE (10000); //at least we'll be able to reach capitol
  15. ResourceObjective::ResourceObjective(TResources & Res, Goals::TSubgoal Goal)
  16. : resources(Res), goal(Goal)
  17. {
  18. }
  19. bool ResourceObjective::operator<(const ResourceObjective & ro) const
  20. {
  21. return goal->priority < ro.goal->priority;
  22. }
  23. ResourceManager::ResourceManager(CPlayerSpecificInfoCallback * CB, VCAI * AI)
  24. : ai(AI), cb(CB)
  25. {
  26. }
  27. void ResourceManager::setCB(CPlayerSpecificInfoCallback * CB)
  28. {
  29. cb = CB;
  30. }
  31. void ResourceManager::setAI(VCAI * AI)
  32. {
  33. ai = AI;
  34. }
  35. bool ResourceManager::canAfford(const TResources & cost) const
  36. {
  37. return freeResources().canAfford(cost);
  38. }
  39. TResources ResourceManager::estimateIncome() const
  40. {
  41. TResources ret;
  42. for (const CGTownInstance * t : cb->getTownsInfo())
  43. {
  44. ret += t->dailyIncome();
  45. }
  46. for (const CGObjectInstance * obj : ai->getFlaggedObjects())
  47. {
  48. if (obj->ID == Obj::MINE)
  49. {
  50. switch (obj->subID)
  51. {
  52. case Res::WOOD:
  53. case Res::ORE:
  54. ret[obj->subID] += WOOD_ORE_MINE_PRODUCTION;
  55. break;
  56. case Res::GOLD:
  57. case 7: //abandoned mine -> also gold
  58. ret[Res::GOLD] += GOLD_MINE_PRODUCTION;
  59. break;
  60. default:
  61. ret[obj->subID] += RESOURCE_MINE_PRODUCTION;
  62. break;
  63. }
  64. }
  65. }
  66. return ret;
  67. }
  68. void ResourceManager::reserveResoures(TResources & res, Goals::TSubgoal goal)
  69. {
  70. if (!goal->invalid())
  71. tryPush(ResourceObjective(res, goal));
  72. else
  73. logAi->warn("Attempt to reserve resources for Invalid goal");
  74. }
  75. Goals::TSubgoal ResourceManager::collectResourcesForOurGoal(ResourceObjective &o) const
  76. {
  77. auto allResources = cb->getResourceAmount();
  78. auto income = estimateIncome();
  79. Res::ERes resourceType = Res::INVALID;
  80. TResource amountToCollect = 0;
  81. typedef std::pair<Res::ERes, TResource> resPair;
  82. std::map<Res::ERes, TResource> missingResources;
  83. //TODO: unit test for complex resource sets
  84. //sum missing resources of given type for ALL reserved objectives
  85. for (auto it = queue.ordered_begin(); it != queue.ordered_end(); it++)
  86. {
  87. //choose specific resources we need for this goal (not 0)
  88. for (auto r = Res::ResourceSet::nziterator(o.resources); r.valid(); r++)
  89. missingResources[r->resType] += it->resources[r->resType]; //goal it costs r units of resType
  90. }
  91. for (auto it = Res::ResourceSet::nziterator(o.resources); it.valid(); it++)
  92. {
  93. missingResources[it->resType] -= allResources[it->resType]; //missing = (what we need) - (what we have)
  94. vstd::amax(missingResources[it->resType], 0); // if we have more resources than reserved, we don't need them
  95. }
  96. vstd::erase_if(missingResources, [=](const resPair & p) -> bool
  97. {
  98. return !(p.second); //in case evaluated to 0 or less
  99. });
  100. if (missingResources.empty()) //FIXME: should be unit-tested out
  101. {
  102. logAi->error("We don't need to collect resources %s for goal %s", o.resources.toString(), o.goal->name());
  103. return o.goal;
  104. }
  105. float goalPriority = 10; //arbitrary, will be divided
  106. for (const resPair & p : missingResources)
  107. {
  108. if (!income[p.first]) //prioritize resources with 0 income
  109. {
  110. resourceType = p.first;
  111. amountToCollect = p.second;
  112. goalPriority /= amountToCollect; //need more resources -> lower priority
  113. break;
  114. }
  115. }
  116. if (resourceType == Res::INVALID) //no needed resources has 0 income,
  117. {
  118. //find the one which takes longest to collect
  119. typedef std::pair<Res::ERes, float> timePair;
  120. std::map<Res::ERes, float> daysToEarn;
  121. for (auto it : missingResources)
  122. daysToEarn[it.first] = (float)missingResources[it.first] / income[it.first];
  123. auto incomeComparer = [&income](const timePair & lhs, const timePair & rhs) -> bool
  124. {
  125. //theoretically income can be negative, but that falls into this comparison
  126. return lhs.second < rhs.second;
  127. };
  128. resourceType = boost::max_element(daysToEarn, incomeComparer)->first;
  129. amountToCollect = missingResources[resourceType];
  130. goalPriority /= daysToEarn[resourceType]; //more days - lower priority
  131. }
  132. if (resourceType == Res::GOLD)
  133. goalPriority *= 1000;
  134. return Goals::sptr(Goals::CollectRes(resourceType, amountToCollect));
  135. }
  136. Goals::TSubgoal ResourceManager::whatToDo() const //suggest any goal
  137. {
  138. if (queue.size())
  139. {
  140. auto o = queue.top();
  141. auto allResources = cb->getResourceAmount(); //we don't consider savings, it's out top-priority goal
  142. if (allResources.canAfford(o.resources))
  143. return o.goal;
  144. else //we can't afford even top-priority goal, need to collect resources
  145. return collectResourcesForOurGoal(o);
  146. }
  147. else
  148. return Goals::sptr(Goals::Invalid()); //nothing else to do
  149. }
  150. Goals::TSubgoal ResourceManager::whatToDo(TResources &res, Goals::TSubgoal goal)
  151. {
  152. TResources accumulatedResources;
  153. auto allResources = cb->getResourceAmount();
  154. ResourceObjective ro(res, goal);
  155. tryPush(ro);
  156. //check if we can afford all the objectives with higher priority first
  157. for (auto it = queue.ordered_begin(); it != queue.ordered_end(); it++)
  158. {
  159. accumulatedResources += it->resources;
  160. if (!accumulatedResources.canBeAfforded(allResources)) //can't afford
  161. return collectResourcesForOurGoal(ro);
  162. else //can afford all goals up to this point
  163. {
  164. if (it->goal == goal)
  165. return goal; //can afford immediately
  166. }
  167. }
  168. return collectResourcesForOurGoal(ro); //fallback, ever needed?
  169. }
  170. bool ResourceManager::notifyGoalCompleted(Goals::TSubgoal goal)
  171. {
  172. if (goal->invalid())
  173. logAi->warn("Attempt to complete Invalid goal");
  174. bool removedGoal = false;
  175. while (true)
  176. { //unfortunatelly we can't use remove_if on heap
  177. auto it = boost::find_if(queue, [goal](const ResourceObjective & ro) -> bool
  178. {
  179. return ro.goal == goal || ro.goal->fulfillsMe (goal);
  180. });
  181. if (it != queue.end()) //removed at least one
  182. {
  183. queue.erase(queue.s_handle_from_iterator(it));
  184. logAi->debug("Removed goal %s from ResourceManager.", it->goal->name());
  185. removedGoal = true;
  186. }
  187. else //found nothing more to remove
  188. return removedGoal;
  189. }
  190. return removedGoal;
  191. }
  192. bool ResourceManager::updateGoal(Goals::TSubgoal goal)
  193. {
  194. //we update priority of goal if it is easier or more difficult to complete
  195. if (goal->invalid())
  196. logAi->warn("Attempt to update Invalid goal");
  197. auto it = boost::find_if(queue, [goal](const ResourceObjective & ro) -> bool
  198. {
  199. return ro.goal == goal;
  200. });
  201. if (it != queue.end())
  202. {
  203. it->goal->setpriority(goal->priority);
  204. auto handle = queue.s_handle_from_iterator(it);
  205. queue.update(handle); //restore order
  206. return true;
  207. }
  208. else
  209. return false;
  210. }
  211. bool ResourceManager::tryPush(ResourceObjective & o)
  212. {
  213. auto goal = o.goal;
  214. auto it = boost::find_if(queue, [goal](const ResourceObjective & ro) -> bool
  215. {
  216. return ro.goal == goal;
  217. });
  218. if (it != queue.end())
  219. {
  220. auto handle = queue.s_handle_from_iterator(it);
  221. vstd::amax(goal->priority, it->goal->priority); //increase priority if case
  222. //update resources with new value
  223. queue.update(handle, ResourceObjective(o.resources, goal)); //restore order
  224. return false;
  225. }
  226. else
  227. {
  228. queue.push(o); //add new objective
  229. logAi->debug("Reserved resources (%s) for %s", o.resources.toString(), goal->name());
  230. return true;
  231. }
  232. }
  233. bool ResourceManager::hasTasksLeft() const
  234. {
  235. return !queue.empty();
  236. }
  237. TResources ResourceManager::reservedResources() const
  238. {
  239. TResources res;
  240. for (auto it : queue) //substract the value of reserved goals
  241. res += it.resources;
  242. return res;
  243. }
  244. TResources ResourceManager::freeResources() const
  245. {
  246. TResources myRes = cb->getResourceAmount();
  247. auto towns = cb->getTownsInfo();
  248. if (towns.size()) //we don't save for Capitol if there are no towns
  249. {
  250. if (std::none_of(towns.begin(), towns.end(), [](const CGTownInstance * x) -> bool
  251. {
  252. return x->builtBuildings.find(BuildingID::CAPITOL) != x->builtBuildings.end();
  253. }))
  254. {
  255. myRes[Res::GOLD] -= GOLD_RESERVE;
  256. //what if capitol is blocked from building in all possessed towns (set in map editor)?
  257. }
  258. }
  259. myRes -= reservedResources(); //substract the value of reserved goals
  260. for (auto & val : myRes)
  261. vstd::amax(val, 0); //never negative
  262. return myRes;
  263. }
  264. TResource ResourceManager::freeGold() const
  265. {
  266. return freeResources()[Res::GOLD];
  267. }
  268. TResources ResourceManager::allResources() const
  269. {
  270. return cb->getResourceAmount();
  271. }
  272. TResource ResourceManager::allGold() const
  273. {
  274. return cb->getResourceAmount()[Res::GOLD];
  275. }